10

任务是用标签和属性替换<img>给定字符串中的所有标签作为内部文本。在寻找答案时,我发现了类似的问题<div>src

<?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.

问题:如何升级脚本ant得到这个结果:

this is something with an <div>test.png</div>  in it.
4

2 回答 2

15

这是 PHPDOMDocument类擅长的问题:

$dom = new DOMDocument();
$dom->loadHTML($content);

foreach ($dom->getElementsByTagName('img') as $img) {
    // put your replacement code here
}

$content = $dom->saveHTML();
于 2012-12-09T01:36:23.630 回答
3
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;
于 2015-08-03T11:34:59.823 回答