2012-08-23 60 views
0

我試圖preg_replace來檢測字符串中的鏈接。下面的例子PHP只有preg_replace鏈接

$descriptionlink = "This is a test www.google.com"; 
$descriptionlink = preg_replace('/.*?\b((?:(?:https?|ftp|file):\/\/|www\.|ftp\.)?[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]\.[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]).*?/i', '$1', $descriptionlink); 

它工作得很好,如果有一個字符串中的鏈接,只有像我想要的鏈接回聲。現在,如果字符串只是文本,它會回顯文本。如果它沒有鏈接,我不想看到字符串中的文字。輸出

例如我想

input - This is a test www.google.com 
output - www.google.com 

,上面的偉大工程,但它會做到這一點和回聲出下面的文本,如果沒有鏈接

input - This is a test 
output - This is a test 

我所要的輸出爲空,如果是隻是文字。

感謝

+0

的Preg什麼也沒有取代它呢? –

+1

@ColeJohnson我的意思是我只想顯示鏈接而不是文本。現在它顯示了兩者。謝謝 –

+0

你能用一個想要的輸出顯示一個示例輸入嗎? –

回答

0
$descriptionlink = preg_replace('/.*?((?:(?:https?):\/\/|www\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]).*?|.*/i', '$1', $descriptionlink); 
+1

它現在不會回顯鏈接。謝謝 –

+0

在我的測試環境它確實...也許是因爲邊界(線...) ...我編輯答案... – TheHe

+1

對不起,在腳本中的錯字謝謝! –

0

這個......將取代所有除鏈接...

$descriptionlink = preg_replace('/.*?\b((?:(?:https?|ftp|file):\/\/|www\.|ftp\.)?[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]\.[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]).*?/i', '$1', $descriptionlink); 
+0

capture-group 1是鏈接...將其更改爲任何您想要的內容,例如'$1' – TheHe

+1

感謝您的回答 –

+1

如果沒有鏈接,它會顯示文本。我如何刪除文本 –