Search code examples
phppreg-match

php preg_match numbers 2000 - 2999


I'm trying to write an if statement that continues if $var equals any number 2000 - 2999 inc.

if ( preg_match( '/^20.*/', $var) ) continue;

This seems to work, but would that also match on 20123456 or 20001-1234-2345 etc ?

How do I limit it to just 2000 - 2999 inclusive ?

Thanks


Solution

  • The simplest way with regex:

    if ( preg_match( '/^2[0-9]{3}$/', $var) ) continue;
    

    [0-9] matches any digit character. {3} says match it exactly 3 times. So it would match 000, 001, 120, 999, etc... $ matches the end of the string.

    See this regex101 link for more information. (Use the unit tests on the left to make sure the function is matching what you're looking for)