0

我有一个字符串

   <p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595" style="float: none;" /></p>

以及我想在其中添加新字符串的内容

<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595/test_image.jpg" style="float: none;" /></p>

我尝试过 DOMDocument 和 Simple HTML 解析器,但不能这样做。请看一看。

4

1 回答 1

1

这将附加/test_image.jpgsrc每个图像元素的pyro-image.

演示

$html = '<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595" style="float: none;" /></p>';

$d = new DOMDocument();
$d->loadHTML($html);

$xp = new DomXPath($d);
$class = 'pyro-image';
$nodes = $xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($nodes as $n)
{
    $n->setAttribute('src', (string)$n->getAttribute('src') . '/test_image.jpg');
    echo $d->saveXML($n->parentNode);

    // note - can use saveHTML() instead but only from PHP 5.3.6
}

输出

<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595/test_image.jpg" style="float: none;"/></p>
于 2012-12-11T10:56:28.497 回答