0

我使用一个脚本来检测字符串中的 url 并将其替换为锚标记:

$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$mytext);
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string);
$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<a href=\"mailto:$1\">$1</a>",$string);

它工作正常,除非它遇到图像标签。例如:

<img src="http://www.xx.com/img.jpg" alt=""/>

会变成:

<img src="<a href="http://www.xx.com/img.jpg">http://www.xx.com/img.jpg</a>http://www.xx.com/img.jpg" alt=""/>

如果' src=" ' 就在它之前,我应该如何修改这个 preg_replace 以便不改变 url ?

谢谢

4

1 回答 1

0

尝试/在每个正则表达式的末尾添加这个:

(?<!\.(?:jpe?g|png|gif))

这应该检查以确保最后一位(扩展部分)不是标准图像格式之一。

于 2013-03-05T22:57:30.773 回答