2011-10-04 142 views
0

可能重複:
PHP if string contains URL isolate it提取網址

我想用某種形式的正則表達式來提取任何類型的鏈接像www.google.com或http://google.comhttps://google.com或只是從一個字符串google.com

我已經使用這樣的東西..但它只檢測鏈接與http和https

$regex ="/(https?:\/\/[^\s]+)/"; 
$string ="is there a link http://google.com in this string?"; 
preg_match($regex, $string,$matches); 
print_r($matches); 

我得到的輸出是

Array ([0] => http://google.com) 

我想檢測所有類型的字符串中的可能聯繫。

任何幫助將不勝感激! :)

+0

還有其他幾個參考文獻。搜索此網站獲取'[php] preg_match網址' –

+1

我不認爲這是鏈接問題的完全重複。 OP想要覆蓋更多的鏈接模式,並且給定的鏈接不會幫助OP。 – stema

回答

0

只是利用交替來覆蓋其他模式。嘗試是這樣的:

(https?:\/\/[^\s]+|\bwww\.[^\s]+|[^\s]+\.(?:com|org|uk)\b) 

見這裏online on Regexr

,第一部分是你的。第二部分將匹配以www.開頭的所有內容,第三部分將匹配以列表(com | org | uk)結尾的所有內容。你可以添加任何你想匹配的域名到這個列表。

我很確定這會匹配很多東西,這不是一個有效的URL,但如果你對你的正則表達式感到滿意,可能其他兩種模式也適合你的需要。

1

我用超鏈接替換所有的URL,但你可以做任何你想做的事情。

function formatUrlsInText($text) 
{ 

    $reg_exUrl = "%^((http|https|ftp|ftps?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i"; 
    preg_match_all($reg_exUrl, $text, $matches); 
    $usedPatterns = array(); 
    foreach($matches[0] as $pattern){ 
     if(!array_key_exists($pattern, $usedPatterns)){ 
      $usedPatterns[$pattern]=true; 
      $text = str_replace ($pattern, "<a href='{$pattern}' rel='nofollow' target='_blank'>{$pattern}</a> ", $text); 
     } 
    } 
    return $text; 
}