Regex using PHP, any non-zero number containing the digits 0-9
I have this regex:
/^[0-9]+$/i
Used in this code:
preg_match('/^[0-9]+$/i', $var);
I want the following to be true: $var = 1; $var = 50; $var = 333;
And the following to be false: $var = 0; $var = 01; $var = 'abc';
I think what I have works so far except for the "0" part..?
I went through this g开发者_JAVA百科uide (http://www.phpf1.com/tutorial/php-regular-expression.html) but was unable to come up with a complete answer.
Any help would be appreciated, thanks!
/^[1-9][0-9]*$/
Means: A non-zero digit followed by an arbitrary number of digits (including zero).
just check for a non zero digit first then any number of other digits
preg_match('/^[1-9][0-9]*$/', $var);
There are a couple of ways you can do this:
/^[1-9][0-9]*$/
or
/^(?!0)[0-9]+$/
Either one of these should be fine. The first one should be more or less self-explanatory, and the second one uses a zero-width negative lookahead assertion to make sure the first digit isn't 0.
Note that regex isn't designed for numeric parsing. There are other ways of doing it that will be faster and more flexible in terms of numeric format. For example:
if (is_numeric($val) && $val != 0)
...should pick up any nonzero number, including decimals and scientific notation.
You can solve this by forcing the first digit to be different from 0 with '/^[1-9][0-9]*$/'
With your list of exemples:
foreach (array('1', '50', '333', '0', '01', 'abc') as $var) {
echo $var.': '.(preg_match('/^[1-9][0-9]*$/', $var) ? 'true' : 'false')."\n";
}
This script gives the following results:
$ php test.php
1: true
50: true
333: true
0: false
01: false
abc: false
精彩评论