2012-02-09 112 views
-1

可能重複:
Find url from string with 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]+)[email protected])?(?:(?:[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); 
+0

那麼,顯然你使用的模式不是「完美的」:) 試試這個: http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to -check-if-a-string-is-a-url- – alfasin 2012-02-09 19:07:49

回答

2

使用這個表達式:\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))

您可以測試它:http://gskinner.com/RegExr/

我剛纔測試了這個正則表達式與您的網址和完美的作品。

+0

gskinner是一款出色的工具btw +1 – hackartist 2012-02-09 19:34:15