PHP-替换< img>标签并返回src [英] PHP - replace <img> tags and return src
本文介绍了PHP-替换< img>标签并返回src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任务是将给定字符串中的所有<img>
标签替换为<div>
标签和src
属性作为内部文本.
在寻找答案时,我发现了类似的问题
Mission is to replace all <img>
tags in given string with <div>
tags and src
property as inner text.
In search for the answer I found 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.
推荐答案
这是PHP的 DOMDocument
类擅长于:
This is the kind of problem that PHP's DOMDocument
class excels at:
$dom = new DOMDocument();
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('img') as $img) {
// put your replacement code here
}
$content = $dom->saveHTML();
这篇关于PHP-替换< img>标签并返回src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文