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

Posted

技术标签:

【中文标题】PHP - 替换 <img> 标签并返回 src【英文标题】:PHP - replace <img> tags and return src 【发布时间】:2012-11-26 20:26:24 【问题描述】:

任务是用&lt;div&gt;标签和src属性替换给定字符串中的所有&lt;img&gt;标签作为内部文本。 在寻找答案时我找到了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.

【问题讨论】:

您不想使用正则表达式来解析 html。他们不能胜任这项任务。您的正则表达式解决方案非常脆弱。 htmlparsing.com/regexes.html 解释了原因。 【参考方案1】:

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

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

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


$content = $dom->saveHTML();

【讨论】:

$img-&gt;setAttribute( 'src', $new_src_url );【参考方案2】:
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;

【讨论】:

以上是关于PHP - 替换 <img> 标签并返回 src的主要内容,如果未能解决你的问题,请参考以下文章

用 php 将 img 替换为 background-image div

php正则表达式提取img alt/title标签并替换

php如何在img后面加br标签

php匹配<img/>,添加width,height

替换 cycle2.js 中的 <img> 标签

正则把<img src="**">替换成<img data-original="**">把img标签中的src属性名称替换成data-o