Kala Mei Kala Mei - 5 months ago 8
PHP Question

Using regex to get urls with some rules

A string contain many urls, how to get urls start not with

[url]
, and end not with
[/url]


Example:


A string contain many urls: http://stackoverflow.com/1 [url]http://stackoverflow.com/2[/url] http://stackoverflow.com/3 [url]http://stackoverflow.com/4[/url], how to get match urls?


In this sample, need only return
http://stackoverflow.com/1
and
http://stackoverflow.com/3
.

Answer

(?<!\[url\])(?![^\s]+\[\/url\])http[^\s]*

This will grab the all the URLs not enclosed in the tags you mentioned ([url] and [\url]). Note that this works for every URL, not just the one you listed (i.e http://stackoverflow.com), which I think is what you want. You can see the explanations and live demo for each rule on Regex101 - Link: https://regex101.com/r/wN9aX0/3

Comments