【问题标题】:PHP - replace <img> tags and return srcPHP - 替换 <img> 标签并返回 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 解释了原因。

标签: php regex html-parsing


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-10-16
    相关资源
    最近更新 更多