Brian Leishman
Brian Leishman

Reputation: 8575

PHP RegEx Replace All URLs That Aren't Images

I'm currently using this regular expression to capture all URLs in a string, which could be multiple lines and contain any other sort of text, which is working perfectly for normal URLs. But I want to replace image URLs in a different way, so my current expression can't match those URLs.

My current expression is

(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w\/_\.#-]*(\?\S+)?[^\.\s])?)?)

But I don't want it to match URLs that end with (jpe?g|png|gif), and I haven't been able to figure out exactly how to use the RegEx negative lookaheads.

Upvotes: 1

Views: 153

Answers (1)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

Really, it would be easier to just check the urls afterwards by matching all urls and then checking them. Or use preg_replace_callback which would allow you to check additional stuff on the match and add additional logic to check what type of url it is. You just switch the replacement value with a callback and whatever is returned from the callback is what is replaced.

But, if you wanted to use a single regex, put something like this at the start of your pattern: (?!\S+(?:png|gif|jpe?g)) which will force a url to not match if it has .(png|gif|jpe?g) anywhere in the string.

Upvotes: 3

Related Questions