【发布时间】: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 " <a href='http://mywebsite.com/".$matches[0]."'> <font color ='black' >View Image</font> </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 标签的所有不同编码选项而陷入地狱……