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

时间:2012-12-09 01:23:03

标签: 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.

问题:如何升级脚本蚂蚁得到这个结果:

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

2 个答案:

答案 0 :(得分:8)

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

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

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

$content = $dom->saveHTML();

答案 1 :(得分:0)

$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace('/(<)([img])(\w+)([^>]*>)/', '<div>$1</div>', $content); 
echo $content;