1

将所有 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
4

1 回答 1

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;

也不推荐<font>使用<span>因为标签,而不是标签。<font>

于 2013-05-31T06:53:17.270 回答