【问题标题】:replace all img tag with anchor tag用锚标签替换所有 img 标签
【发布时间】:2013-05-26 22:09:15
【问题描述】:

将所有 img 标签替换为锚标签,其中 img src 属性值应为锚标签 href 属性值。我不知道如何编写模式以匹配整体并替换 img 标记并返回带有 href 值的锚标记作为 img 标记的 src 属性值在以下处理函数中。

我在下面尝试过:

$pattern = '/<img[^>]+>/i'; 
$callback_fn = 'process';   
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches) 
{
        print_r($matches);
    return "&nbsp;&nbsp;<a href='http://mywebsite.com/".$matches[0]."'> <font color ='black' >View Image</font>&nbsp;&nbsp;</a>";
}       
echo $content;

例如:

$string = "this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one";

输出是:

this is dummy string View Image this is another sentesnces View Image this is third one

这里,查看图片是链接

http://mywebsite.com/<img src="imageone.jpg" alt="" />

但我想要这个:

http://mywebsite.com/imageone.jpg

【问题讨论】:

  • 不要手动操作,使用更适合您工作的工具:看看 phps DOM 扩展。否则,您将因 img 标签的所有不同编码选项而陷入地狱……

标签: php preg-replace-callback


【解决方案1】:

这样试试

$pattern = '/<img.+src=(.)(.*)\1[^>]*>/iU';
$callback_fn = 'process';
$string = 'this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one';
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches)
{
    return "&nbsp;&nbsp;<a href='http://mywebsite.com/".$matches[2]."'> <font color ='black' >View Image</font>&nbsp;&nbsp;</a>";
}
echo $content;

同时使用&lt;span&gt; 代替&lt;font&gt; 标签,因为&lt;font&gt; 已被弃用。

【讨论】: