Search code examples
phpregexpreg-match

Special Expression not allowed - Regular Expression in PHP


I am trying match my String to not allow the case: for example 150x150 from the image name below:

test-string-150x150.png

I am using the following pattern to match this String:

/^([^0-9x0-9]+)\..+/

It works fine, Except in such a case:

teststring.com-150x150.jpg

What i need to get - the mask must disallow only dimensions in the end of string, here is some examples:

test-string-150x150.png > must disallow

any-string.png > allow

200x200-test.png > allow

1x1.png-100x100.jpg > disallow


Solution

  • You could use a negative lookahead to assert that the string does not contain the sizes followed by a dot and 1+ word characters till the end of the string.

    ^(?!.*\d+x\d+\.\w+$).+$
    

    Explanation

    • ^ Start of string
    • (?! Negative lookahead, assert what is on the right is not
      • .* Match 0+ occurrences of any char except a newline
      • \d+x\d+ Match the sizes format, where \d+ means 1 or more digits
      • \.\w+$ Match a dot, 1+ word characters and assert the end of the string $
    • ) Close lookahead
    • .+ Match 1+ occurrences of any char except a newline
    • $ End of string

    Regex demo