Reputation: 47
I'm using this code to replace urls in a string
preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)
How do I do the same thing, but keeping urls that match a certain pattern (ie start with a domain I want to keep)?
Update
Turns out that the urls I want to keep include relative urls, so I now want to eliminate all urls that don't match the given url pattern and are not relative links.
Upvotes: 0
Views: 465
Reputation: 44823
You need a negative look-ahead assertion:
preg_replace('#<a(?![^>]+?href="?http://keepthisdomain.com/foo/bar"?).*?>(.*?)</a>#i', '\1', $text);
Edit: If you want to match only relative domains, the logic is the same. Just take out the protocol and domain name:
preg_replace('#<a(?![^>]+?href="?/?path/to/foo/bar"?).*?>(.*?)</a>#i', '\1', $text);
The ?
after "
and /
means that those characters are optional. So, the second example will work for either path/to/foo/bar
or /path/to/foo/bar
.
Upvotes: 1