2016-12-14 73 views
0

我需要刪除字符串中的所有鏈接,但保留我的網站的URL在字符串中。正則表達式來禁用URL的,但只啓用一個

這是我到目前爲止所嘗試的:

example.com是我的域名。

(https?:\/\/)?((?:(\w+-)*\w+)\.)+(?:[a-z]{2})(\/?\w?-?=?_?\??&?)+[\.]?(?!example.com) 

樣品輸入包括:

http://website.com 
https://www.website.com 
http://www.website.com 
string http://website.com 
http://website.com string 
string example.com 
string www.example.com 
string http://website.com www.example.com 
www.website.com example.com 

但是,這是行不通的。

+0

請輸入和輸出樣品。 – bassxzero

回答

2

你這樣做更簡單;現在,你的正則表達式包含了許多與你寫的問題無關的組和條件。

簡單的版本(需要協議)

這裏有一個正則表達式,你想要做什麼,假設鏈接包含協議(httphttps):

/https?:\/\/(?!(www\.)?example\.com)\S+\s*/gi 

Demo

這看起來爲http ,可選地s://,之後不是www.example.comexample.com,那麼一串非空白cha (\S+)和任何尾隨空格(\s*)。只需用空字符串替換任何匹配即可。

示例PHP代碼(3v4l.org demo):

$re = '/https?:\/\/(?!(www\.)?example\.com)\S+\s*/i'; 
$str = 'http://foo.com 
https://foo.com/bar/baz/?blah=boo&bah=humbug#something 
http://google.com/ 
http://example.com 
http://example.com/ 
https://example.com 
https://example.com/ 
https://example.com/bar/baz/?blah=boo&bah=humbug#something'; 
$subst = ''; 

$result = preg_replace($re, $subst, $str); 

echo "The result of the substitution is ".$result; 

輸出:

The result of the substitution is http://example.com 
http://example.com/ 
https://example.com 
https://example.com/ 
https://example.com/bar/baz/?blah=boo&bah=humbug#something 

更復雜的版本(不要求協議)

如果你想去掉像foo.com甚至事(沒有協議),這不是真的「鏈接」,你必須得到更多的創意:

/https?:\/\/(?!(www\.)?example\.com)\S+\s*|(?!(www\.)?example.com)\b\w+\.[a-z]{2,}[\/?&=#\S]+\s*/gi 

這是regex101 demo3v4l.org demo。這第一部分是和以前一樣,但包含的替代條款:

(?!(www\.)?example.com)\b\w+\.[a-z]{2,}[\/?&=#\S]+\s* 

此說忽略它是否與任何www.example.comexample.com開始下文。然後它會嘗試匹配一個字邊界(\b),一個「單詞」字符串(\w+),一個句點(\.),兩個或多個字母([a-z]{2,}),可能跟在域名後面的任何其他字符([\/?&=#\S]+),和任何尾隨的空格(\s*)。

+0

這工作,但我怎麼也沒有http或https捕獲鏈接?甚至沒有'www'? – Nedas

+0

@Nedas我沒有意識到根據你最初的問題,你試圖捕捉沒有協議的「鏈接」。我編輯了我的答案,告訴你如何做到這一點。它可以使用或不使用「www」。請注意:真正的域名驗證要複雜得多,並且在某些情況下,鏈接可以有效地包含空格。我的解決方案沒有考慮涉及例如國際域(非拉丁字符集)的非常奇怪的邊緣案例,但它可以處理99.99%的URL,沒有任何問題。 –

+0

謝謝你的幫助! – Nedas