2017-03-07 161 views
0

我不擅長正則表達式。正則表達式模式來匹配有或沒有http(s)和沒有標籤的url

我在做什麼?我想匹配特殊字符串中的所有網址。

基本上,我想匹配所有的網址,用<a> - 標籤,除了現有的<a> - 標籤。

例如,下面的字符串應該匹配:

喂!我是一個文本點擊這裏,有很多 的網址www.aon.at?this=true和www.aon.at.都應該正確匹配 http://www.aon.at也工作aon.at/this?true

應該怎樣匹配:

喂!我是一個文本< A HREF = 'www.aon.at'>點擊這裏</A>,有網址www.aon.at?this=truewww.aon.at的很多 。都應該正確匹配 http://www.aon.at也工作aon.at/this?true

我已經試過正則表達式從Linkify Regex Function PHP Daring Fireball Method

(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»「」‘’])) 

https://regex101.com/在頁面上,但它不是按我希望的方式工作。正如你所看到的,正則表達式匹配<a> - 標籤,我不知道如何刪除它。

enter image description here

回答

0

沒關係,找到了解決辦法了。

憑藉該解決方案,一切工作正常

$pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`\!()\[\]{};:\'".,<>?«»「」‘’]))';  
return preg_replace("!$pattern!i", "<a href=\"\\0\" rel=\"nofollow\" target=\"_blank\">\\0</a>", $str);