[英]How to convert a capturing group to a non-capturing group in this regex?
我正在嘗試使用正則表達式將文本中的所有 url 替換為超鏈接。 網址必須以http://
或https://
開頭。 而且它們必須包含一些 TLD,例如.com
、 .org
或.co.uk
等。
下面是我在PHP
中的regex
模式:
$pattern = "/(http)+(s)?:\/\/(\S)+(\.){1}/i";
所以如果你使用下面的代碼:
$str = "this http://dd is a String http://www.example.com and this a String https://anotherexample.co.uk";
echo preg_replace($pattern, "<a href='$0' target='_blank'>$0</a>", $str);
它給了我以下輸出:
您可以看到 TLD 部分未包含在超鏈接中。 那么如何將捕獲組(\.){1}
轉換為非捕獲組以覆蓋 TLD?
你可以試試這個:
$pattern = "/https?:\/\/(\S)+(\.\w{1,4})+/i"
echo preg_replace($pattern, "<a href='$0' target='_blank'>$0</a>", $str);
在模式中:
https?
: http 或 https
(\.\w{1,4})+
:像.co .com或類似.co.uk的 TLD,這里每個 TLD 的最大長度為 4,但您可以更改它。
使用以下模式:
https?:\/\/[az]+\.[az]+[.az]* /i
?
[az]+
捕獲 'https' 后的第一組字母[.az]*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.