问题
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?- eitherhttporhttps://- a literal char sequence\S+- one or more non-whitespace symbolsi- 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