1

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.

2
  • 1
    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. 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. Example Commented Oct 8, 2015 at 20:22
  • Yep that, did it. I was almost there, but I didn't try the very beginning of that string, but that worked perfectly. I might have to look into that other function you mentioned though, as I was unaware of such a function, but it sounds like I'd have a lot more control and power over what I'm doing. Thank you! Commented Oct 8, 2015 at 20:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.