简体   繁体   中英

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

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

If I understand your question, you're trying to find image names that do not include the image dimensions. If so, try this:

/^(?![\w-\.]+(\d+x\d+))[\w-\.]+\.\w+$/gm

For details about this code, please see regexr.com/4tmd1 . This site is a great place to play around with regexes to make sure you're getting the results you expect.

Be aware that the exact syntax of the regular expression depends on the regex engine used by whatever program you're running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM