Search code examples
phpregexurlpreg-matchurl-parsing

Match urls with a specific signature


I have this preg_match rule:

preg_match( '#(http:\/\/(www.)?imgur.com)\/(gallery\/)?(([-|~_0-9A-Za-z]+)&?.*?)#i', $link, $matches )

this matches these:

http://imgur.com/xxxx
http://www.imgur.com/xxxx
http://imgur.com/gallery/xxxx

How I can avoid to match with imgur.com/a/xxxx#xxxx ?


Solution

  • I am not sure if this is what you want:

    preg_match( '#(http:\/\/(www.)?imgur.com)\/(?!a)(gallery\/)?(([-|~_0-9A-Za-z]+)&?.*?)#i', $link, $matches )
    

    With this url like http://imgur.com/a/xxxxxx won't match.

    PS: Though depending on what you are doing, I think that the regular expression may get unnecessarily complicated and you should try to find simpler methods. Look at my answer here regarding parsing urls: Would a regular expression be best for this problem?