Search code examples
javaphpregexmatchimageurl

Match all URLs exclude jpg,gif,png


I want to match all URLS but exclude image urls from beeing matched with that regex: jpe?g|gif|png .

\b(?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*A-Z0-9+&@#/%=~_|$

The problem is that the part with the exclude is not working like this: (?!jpe?g|gif|png)

Does anyone have a solution for it?

Example:

not Matchen:

http://example.com/example.jpg
http://example.com/example231/example.gif

Match:

http://example.com/example.html
http://example.com/example/?id=4331
http://example.com/example/example/ex_ample/ex-ample/?id=4331  

Solution

  • Just start your regex with (?!.*(?:\.jpe?g|\.gif|\.png)$),

    so if your current regex is \b(?:https?|ftp|file)://..., then merge it to

    (?!.*(?:\.jpe?g|\.gif|\.png)$)\b(?:https?|ftp|file)://...

    Read also PHP URL validation