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

10

使命是将给定字符串中所有的<img>标签替换为<div>标签,并将src属性作为内部文本。在寻找答案时,我发现了类似的问题

<?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.

1
你不应该使用正则表达式来解析HTML。它们无法胜任这项任务。你的正则表达式解决方案非常脆弱。http://htmlparsing.com/regexes.html 解释了原因。 - Andy Lester
3个回答

18

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

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

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

$content = $dom->saveHTML();

10
$img->setAttribute( 'src', $new_src_url ); - Jake

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

0
<?php
$strings = 'awdaw <img src="http://ua1.us/media/media.jpg" alt="Image" width="100" height="100"> aw <img src="http://ua1.us/media/media1awdwa.jpg"> wawadwad';

preg_match_all('/<img[^>]+>/i', $strings, $images);
foreach ($images[0] as $image) {
    preg_match('/src="([^"]+)/i', $image, $replacements);
    $replacement    = isset($replacements[1]) ? $replacements[1] : (isset($replacements[0]) ? $replacements[0] : "image");    
    $strings    = str_replace($image, $replacement, $strings);
}
echo $strings;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接