2012-12-09 43 views
5

任务是将给定字符串中的所有<img>标记替换为<div>标记和src属性作为内部文本。 为了寻找答案,我发现similar questionPHP - 替换<img>标记并返回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解释了原因。 –

回答

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

你不应该依赖正则表达式来解析/转换XML –

7

这是那种PHP的的问题类擅长:

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

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

$content = $dom->saveHTML(); 
+2

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

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