2015-04-05 102 views
3

我發現這個很棒的URL匹配regexp從這裏的另一個答案獲取網址的字符串,但它只適用於後跟空格。如何解決此URL正則表達式匹配字符串末尾的URL?

preg_replace('#(https?|ftp)://[^ ]+ #i', '', $s['Text']); 

我該如何修改它,以便它也會匹配字符串末尾的URL,而後面沒有任何內容?

+0

但後來它匹配的HTTP後輸入的所有內容://,並且不等待有效擴展。還是)感謝你的建議! – 2015-04-05 05:28:01

+0

一個簡單的修復,不會讓你的正則表達式更好地拒絕無效的URL,雖然是'preg_replace('#(https?| ftp):// [^ \ s \ r \ n] +(?:$ | [\ s \ r \ n])#i','',$ s ['Text']);'。這將匹配字符串的末尾或任何空格。你可能也想看一下http://regular-expressions.info教程,它還會解釋非捕獲組「(?:...)」和lookahead,這在這裏可能會有所幫助。 – Archimedix 2015-04-05 06:12:33

+0

您能否將您找到該參考的答案鏈接起來?你有沒有發表評論說它不適合你? – hakre 2015-04-05 07:22:24

回答

1

對於所有類型的URL匹配下面的代碼可以幫助你:

<?php 

$content = '<html> 

<title>Random Website I am Crawling</title> 

<body> 

Click <a href="http://clicklink.com">here</a> for foobar 

Another site is http://foobar.com'; 

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)[email protected])?"; // User and Pass 
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP 
$regex .= "(\:[0-9]{2,5})?"; // Port 
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path 
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query 
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor 


$matches = array(); //create array 
$pattern = "/$regex/"; 

preg_match_all($pattern, $content, $matches); 

print_r(array_values(array_unique($matches[0]))); 
echo "<br><br>"; 
echo implode("<br>", array_values(array_unique($matches[0]))); 


?> 
+0

謝謝 - 這是非常全面和有效的! – 2015-04-05 05:28:16

+0

@MichaelF不客氣;-) – 2015-04-05 05:29:05

+0

嘿阿德里安,我剛剛注意到,這個正則表達式離開了https://www.youtube.com/watch?v=9GorqroigqM的「9GorqroigqM」 - 有關如何解決這個問題的任何建議?它似乎趕上了一切= = – 2015-04-05 05:48:56