PHP - 替换 <img> 标签并返回 src

标签 php regex html-parsing

任务是替换所有<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.

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

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

最佳答案

这是 PHP 的 DOMDocument 的问题类(class)擅长:

$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/

相关文章:

javascript - 如何在 Javascript 中传递 HTML 数据

php - 数据表警告 : table id=dataTables - Ajax error. 404 未找到

javascript - 这个正则表达式前瞻有什么问题?

ruby - 如何获取与某个正则表达式匹配的数组中元素的位置?

javascript - 如何从 Microsoft 更新目录网页获取更新二进制 URL?

php - 从 php 字符串中删除特定标签

javascript - 如何让表单字段动态增加,然后通过post方法提交

php - 我如何使用 GD Library 扭曲图像?

swift - swift 中的正则表达式

python - 查找具有特定属性值的所有标签