如何在php中使用regex来替换html中的ALT和TITLE文本


How to use regex in php to replace ALT and TITLE text in html

我有一个html内容,如下所示。

<img title="" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="">

我想用图像文件的名称(Distchart)替换空的alt和title文本。如何在php中使用preg_replace来做到这一点?执行替换操作后,html应该像一样

<img title="Distchart" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="Distchart">

正如Maxim Kumpan所建议的,最好的方法是使用dom:

$doc = new DOMDocument();
@$doc->loadHTML($html);
$imgs = $doc->getElementsByTagName('img');
foreach($imgs as $img) {
    if (preg_match('~[^/]+(?='.(?>gif|png|jpe?+g)$)~i', $img->getAttribute('src'), $match)) {
        $name = $match[0];
        if ($img->getAttribute('alt')=='') $img->setAttribute('alt', $name);
        if ($img->getAttribute('title')=='') $img->setAttribute('title', $name);
    }
}
$result = $doc->saveHTML();

为此,您最好使用DOMDocument。重新编译HTML是一项忘恩负义的任务。

试试这个

$oldhtml = '<img title="" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="">'
$newhtml = str_replace($oldhtml, 'alt=""', 'alt="Distchart"');