Regex to replace http AND https links

点点圈 提交于 2021-02-07 04:40:32

问题


I have the following preg_replace() function targeting links:

$link = preg_replace(
    "#http://([\S]+?)#Uis", '<a href="http://\\1">(link)</a>', 
    $link
);

It works fine with http links but obviously not with https links. How can I adjust it so that it works with https links as well.


回答1:


Just add s? after http and match the whole link, then use the $0 backreference to refer to it from the replacement pattern:

$link = preg_replace(
    "#https?://\S+#i", '<a href="$0">(link)</a>', 
    $link
);

See the PHP demo

Details:

  • https? - either http or https
  • :// - a literal char sequence
  • \S+ - one or more non-whitespace symbols
  • i - a case insensitive modifier.

Note the U modifier is confusing (? would be written as ??, and the pattern becomes longer), and I suggest removing it.

The s modifier does not make sense if the pattern has no . in it, so it is also redundant, I suggest removing it, too.



来源:https://stackoverflow.com/questions/42929564/regex-to-replace-http-and-https-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!