Search code examples
phpregexpreg-match

preg_match to check "if reach" end of string, not "match character at" end of string


I Google and search this site but doesn't find similar question which I think it's a rare question: I write this RegExp

#<img .+?/font_image/(.{4})\.gif.*?>#

in preg_match() to check this pattern

<img src=".../font_image/xxxx.gif" ...>

In text but sometimes the '>' is missing due to typo.

How can I modify this RegExp to match either a > or end-of-string cases (note: Can't use $ since I wouldn't know what is the last character at end of string, I tried #<img .+?/font_image/(.{4})\.gif.*?># but it doesn't work)?


Solution

  • Just put >$ inside a group delimited by | . Note that don't use char class for this type of OR operation since $ inside a char class should loose it's special meaning.

    <img .+?/font_image/(.{4})\.gif.*?(?:>|$)
    

    DEMO