任务是将给定字符串中的所有<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.

问题:如何升级脚本ant得到以下结果:
this is something with an <div>test.png</div>  in it.

最佳答案

这是PHP的 DOMDocument 类擅长的问题:

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

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

$content = $dom->saveHTML();

关于PHP-替换<img>标记并返回src,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13783760/

10-11 23:09
查看更多