2013-07-22 51 views
-1
function makeLinksInTheContent($html) 
{ 
    $html= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" rel=\"nofollow\" >$3</a>", $html); 
    $html= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" rel=\"nofollow\" >$3</a>", $html); 
    $html= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:[email protected]$3\" rel=\"nofollow\">[email protected]$3</a>", $html); 

    return($html); 
} 

這是我的代碼。preg_replace用於替換匹配網址的字符串

我的需求是自動鏈接的URL。使用preg_replace查找網址並將鏈接設置爲此網址。

例如:「一個頁面包含www.google.com。」如果我將此內容傳遞給makeLinksInTheContent($ html),它將返回「一頁包含www.google.com」。

但是下面的url格式沒有被鏈接。

  1. http://www.google.com
  2. www.test.com()和[] & ^%$#@ + | @#$%^ &()_ +} {:!?「> <,。/;'[] = - 09〜`.co,in,com.com
  3. http://www.test.com()and [] & ^%@#@!+ #$%^ &()_ +} {:「?> <,。/;'[] = - 09〜`.co,in,com.com
  4. https://www.test.com )和[] & ^%$#@!+ |!@#$%^ &()_ +} {:「?> <,。/;'[] = - 09〜`.co,in,com.com
  5. ftp://www.test.com()和[] & ^%$#@!+ |!@#$%^ &()_ +} {:「?> <,。/;'[ ] = - 09〜`.co,in,com.com

我覺得我的正則表達式有一些錯誤。請給我們建議。

回答

1

我可以建議用我的功能 - 只要你的數據測試,對我的作品

function parse_links($string,$mailto=true) 
{ 
    $preg_r = "#(((https?|ftp)(://)?)?[a-zA-Z0-9-_.]{1,64}\.[a-zA-Z0-9-_.]{1,128}\.[a-z]{2,4}(\.[a-z]{2,4})?(/([^ ]{1,256}))?/?)#"; 
    $string = preg_replace($preg_r,"<a href=\"http://$1\">$1</a>",explode(" ",$string)); 
    if($mailto) 
    { 
     $preg_r2 = "/([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z_\-\.][-\w]*[0-9a-zA-Z_\-\.]\.)+[a-zA-Z]{2,9})/"; 
     $string = preg_replace($preg_r2,"<a href=\"mailto:$1\">$1</a>",$string); 
    } 
    return implode(" ",$string); 
} 

只是通過false作爲第二個參數,如果你不希望創建電子郵件鏈接

+0

該死的好做的正則表達式夥計!我喜歡你遵循Apache(可能是web範圍)url標準的方式與給定url的長度。 – DarkMantis