我有一个img
使用DOMDocument扫描字符串中的标签并将它们包装在中的函数div
。
$str = 'string containing HTML';
$doc = new DOMDocument();
$doc->loadHtml(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8'));
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$div = $doc->createElement('div');
$tag->parentNode->insertBefore($div, $tag);
$div->appendChild($tag);
}
return $str;
但是,当将img
包裹在a
标记中时,a
标记将被删除并用替换div
。如何保存a
标签?
目前,
<a href="http://google.com"><img src="srctoimg"/></a>
结果是;
<div><img src="srctoimg"/></div>
而不是;
<div><a href="http://google.com"><img src="srctoimg"/></a></div>
是否可以通过第二个参数传递“通配符”,insertBefore()
或者如何实现?
您可以使用XPath查询来执行此操作。
'//*[img/parent::a or (self::img and not(parent::a))]'
这将让家长对任何img
一个具有标签a
的父母,以及任何图像标签本身对于任何img
不具有即时标签a
父母。
这样,您不必在循环中更改代码。
$str = <<<EOS
<html>
<body>
Image with link:
<a href="http://google.com">
<img src="srctoimg"/>
</a>
Image without link:
<img src="srctoimg"/>
</body>
</html>
EOS;
$doc = new DOMDocument();
$doc->loadHtml(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($doc);
$tags = $xpath->query(
'//*[img/parent::a or (self::img and not(parent::a))]'
);
foreach ($tags as $tag) {
$div = $doc->createElement('div');
$tag->parentNode->insertBefore($div, $tag);
$div->appendChild($tag);
}
echo $doc->saveHTML();
输出(为清楚起见缩进):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
Image with link:
<div>
<a href="http://google.com">
<img src="srctoimg">
</a>
</div>
Image without link:
<div>
<img src="srctoimg">
</div>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句