2012-08-14 55 views
0

可能重复:
Replace URLs in text with HTML linksPHP转换所有URL转换成HTML链接

我传递包含多个URL字符串变量,通过下面的函数来获得同样的事情,只有正确HTML链接。

public function convertUrlsToLinks($text){ 
    return preg_replace('@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $text); 
} 

它根本不起作用。我错过了什么?

代码必须跳过现有的联系,<img>src值(或类似的东西。)

回答

0

假设你已经有一个HTML文档,我有限的网址承认

  • 不开始与“
  • 以http或www

我想出了有这样一个解决方案:

$string = 'lorem ipsum www.foo.bar dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet http://abc.de.fg.com?bar=baz'; 
$rx = '%[^"](?P<link>(?:https?://|www\.)(?:[-_a-z0-9]+\.)+(?:[a-z]{2,4}|museum/?)(?:[-_a-z0-9/]+)?(?:\?[-_a-z0-9+\%=&]+)?(?!</a)(\W|$))%ui'; 
echo preg_replace_callback($rx, function($matches) { 
    return '<a href="'.$matches['link'].'">'.$matches['link'].'</a>'; 
}, $string).PHP_EOL; 

输出字符串是

lorem ipsum<a href="www.foo.bar ">www.foo.bar </a>dolor sit <a href="http://fail.org">http://fail.org</a><img src="www.foo.bar"> amet<a href="http://abc.de.fg.com?bar=baz">http://abc.de.fg.com?bar=baz</a> 

正则表达式应该工作作为intendet,你的一个例子字符串可以帮助