A PHP preg_match integer regex pattern matching example

PHP integer FAQ: Can you demonstrate a regular expression pattern to match an integer?

Interestingly, while reading a book titled Advanced PHP Programming, the author mentions that the PHP is_int function doesn't work exactly the way you expect it to. It just tests to see whether a given variable is typed as an integer or something else, so if you give it a string like "123", it will return false. This is a bad thing when you're trying to test web form data, for example.

As a solution to this problem, the author suggests using a PHP regular expression to match whether the thing you're looking at is an integer, and he uses the following PHP preg_match integer regex pattern to test the match:

if (preg_match('/^\d+$/', $var) 
{
  # do your stuff here ...
}

The PHP preg_match integer regular expression used in this example can be broken down like this:

  • The '^' refers to the beginning of the string.
  • The '\d+' means "one or more numeric digits".
  • The '$' means the end of the line (or end of the string).
  • The $var is the name of the variable you want to test.

Put all this together, and it means "Test the variable $var to see if it contains one or more numeric digits; because the beginning of line and end of line are specified, that's all that can be in this string, digits. For instance, the string '123' is valid, but a string like 'a123' is not valid."

I hope this PHP preg_match integer regular expression pattern (regex pattern) example has been helpful. There's not much to it, but if you're new to regular expressions, it can be helpful to see something like this broken down. It can also be a nice reminder for those of us with bad memories, lol.