任务是将<img>
标记和<div>
属性替换为给定字符串中的所有src
标记作为内部文本。
为了找到答案,我找到了similar question
<?php
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;
?>
结果:
this is something with an (image) in it.
问题:如何升级脚本蚂蚁得到这个结果:
this is something with an <div>test.png</div> in it.
答案 0 :(得分:8)
这是PHP的DOMDocument
类擅长的问题:
$dom = new DOMDocument();
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('img') as $img) {
// put your replacement code here
}
$content = $dom->saveHTML();
答案 1 :(得分:0)
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content);
echo $content;