2012-02-09 15 views
0

我對正則表達式沒有太多的知識。我發現這個代碼,以檢測鏈路或者可以說,以插入寫在textarea的鏈接在php中從textarea拆分url

$url = 'this is just a link http://stackoverflow.com/ to test'; 
$text = preg_replace(" 
    #((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", 
    "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", 
    $url 
); 
echo $text; 

輸出: 這只是一個鏈接stackoverflow.com測試

,但我需要的鏈接分成來自該文本區域的變量。例如變量 $ var = http://stackoverflow.com以便我可以使用該鏈接。

回答

2

你可以試試用這種方法:

$text = 'this is just a link http://stackoverflow.com/ to test'; 
$regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
if(preg_match($regex, $text, $url)) { // $url is now the array of urls 
    // here you should check $url content and length 
    echo $url[0]; // the first one in this case 
} 
else { 
    // no urls found 
} 
+0

謝謝auino。這個對我有用。 @auino – user1199426 2012-02-09 13:03:05

0

嘗試在兩個步驟:

  • 捕獲的URL用的preg_match或preg_match_all,指定& $匹配參數
  • 通過str_replace函數替換URL的您的代碼,循環的比賽
0

你可以如果要捕獲每個匹配並在更換之前進一步操作,或將其保存到別處,請使用pre_replace_callback。您也可以只存儲該正則表達式並稍後進行匹配。我會使用前者,因爲你可能在字符串中有多個鏈接,並且比在自己的循環中運行自己的循環更清潔。