在纯文本中查找URL并将其更改为超链接


finding URL in a text plain and change it to hyperlink

可能重复:
使用php从字符串中查找url

我发现了以下代码:但2个链接没有正确连接。将我的代码保存在php文件中进行测试。

$a = <<<_END
www.coders.com/coder6602.html => Work
www.avan.ir?a=21 => Work
www.limited.ndot.in/kansas/#?w=500 => Not Work
http://www.sales.com => Work
http://www.mediafire.com/?298nlpla3eys9g6 => Work
http://diary.com/files/draft.html و  http://www.logo.net/plogo.swf => Not Work (this is two link)
_END;
/*
<a href="http://limited.ndot.in/kansas/">limited.ndot.in/kansas/</a>#?w=500
<a href="http://diary.com/files/draft.html و  logo.net/plogo.swf">diary.com/files/draft.html و  logo.net/plogo.swf</a>
*/
function strHyperlink($str){
    $pattern_url = '~(?>[a-z+]{2,}://|www'.)(?:[a-z0-9]+(?:'.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:'.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^''/:?*"<>|'n]*[a-z0-9])*/?(?:'?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';
    $str = preg_replace('/http:'/'//','www.', $str);
    $str = preg_replace('/www.www./','www.', $str);
    $str = preg_replace($pattern_url,"<a href='"http://''0'">''0</a>", $str);
    return preg_replace('/www./','',$str);
}
echo strHyperlink($a);

使用此正则表达式:'b((['w-]+://?|www[.])[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/)))

您可以在以下位置进行测试:http://gskinner.com/RegExr/

我刚刚用你的url测试了这个正则表达式,效果非常好。