将所有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
答案 0 :(得分: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 " <a href='http://mywebsite.com/".$matches[2]."'> <font color ='black' >View Image</font> </a>";
}
echo $content;
使用<font>
代替<span>
代码,因为<font>
已被弃用。