PHP preg match / replace?

2019-07-27 13:37发布

I need to read the string $mysting and replace all incident of e.x.

<img src="dummypic.jpg alt="dummy pic">

with

<img src="dummypic.jpg alt="dummy pic" title="dummy pic">

in other words add the title where it is missing, and make the title tag have the same value as the alt tag.

some incident my have additional parameters like border, with, height - and these should be left untouched ...

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-27 13:51

Rather than a regex, have a look into PHP DOMDocument to modify attributes, especially if there will be any complexity.

查看更多
甜甜的少女心
3楼-- · 2019-07-27 13:52

You could use phpQuery or QueryPath to do that:

$qp = qp($html);
foreach ($qp->find("img") as $img) {
    $img->attr("title", $img->attr("alt"));
}
print $qp->writeHTML();

Though it might be feasible in this simple case to resort to an regex:

preg_replace('#(<img\s[^>]*)(\balt=)("[^"]+")#', '$1$2$3 title=$3', $h);

(It would make more sense to use preg_replace_callback to ensure no title= attribute is present yet.)

查看更多
趁早两清
4楼-- · 2019-07-27 13:54

My answer is a link to a well known answer!

RegEx match open tags except XHTML self-contained tags

查看更多
三岁会撩人
5楼-- · 2019-07-27 13:58

You really want to do this using an html parser instead of regexes. Regexes are not suited for html processing.

查看更多
我只想做你的唯一
6楼-- · 2019-07-27 14:05

I usually write quick dirty hacks in these types of situations (usually working with structured data, that might have inconsistencies such as templating engine tags, conditionals, etc.). IMO its a terrible solution, but I can bang out these scripts super fast.

Eg.

<?
$html = '
<img src="dummypic.jpg" alt="dummy pic">
<img src="dummypic2.jpg" alt="dummy pic 2">

blahaahhh

<img src="dummypic.jpg" alt="dummy pic">
<img src="dummypic2.jpg" alt="dummy pic 2">
';

$tags = explode('<img', $html);

for ($i = 1; $i < count($tags); $i++)
{
    $src = explode('src="', $tags[$i]);
    $src = explode('"', $src[1]);
    $src = str_replace('.jpg', '', $src[0]);   

    $tags[$i] = '<img title="' . $src . '"' . $tags[$i];
}

echo implode('', $tags);
查看更多
登录 后发表回答