[英]Using PHP preg_replace to append text to pattern found with regex
I want to append a tag div before and after all tags img. 我想在所有标签img之前和之后添加标签div。
So I have 所以我有
<img src=%random url image% />
And it should be replaced with 并且应该替换为
<div class="demo"><img src=%random url image% /></div>
Can I do it with preg_replace? 我可以用preg_replace吗?
$string = %page source code%;
$find = array("/<img(.*?)\/>/");
$replace = array('<div class="demo">'.$find[0].'</div>');
$result = preg_replace($find, $replace, $string);
But it not work :/ 但这不起作用:/
A better way to parse HTML is using PHPs DOMDocument
and DOMXPath
classes. 解析HTML的更好方法是使用PHP的DOMDocument
和DOMXPath
类。 In your case, you can use XPath to find all the images, then add a div around them as shown in this example: 您可以使用XPath查找所有图像,然后在它们周围添加一个div,如本示例所示:
$html = '<div><img src="http://x.com" /><span>xyz</span><a href="http://example.com"><img src="http://example.com" /></a></div>';
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXpath($doc);
$images = $xpath->query('//img');
foreach ($images as $image) {
$div = $doc->createElement('div');
$div->setAttribute('class', 'demo');
$image->parentNode->replaceChild($div, $image);
$div->appendChild($image);
}
echo $doc->saveHTML();
Output: 输出:
<div>
<div class="demo"><img src="http://x.com"></div>
<span>xyz</span>
<a href="http://example.com">
<div class="demo"><img src="http://example.com"></div>
</a>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.