Regex using PHP, any non-zero number containing numbers 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: false: $ var = 0; $ var = 01; $ var = 'abc';

I think that I have work so far, except for the part "0" ..?

I went through this guide ( http://www.phpf1.com/tutorial/php-regular-expression.html ) but could not find the complete answer.

Any help would be appreciated, thanks!

+4
source share
4 answers
 /^[1-9][0-9]*$/ 

Values: A non-zero digit followed by an arbitrary number of digits (including zero).

+15
source

just check the zero digit first, then any number of other digits

 preg_match('/^[1-9][0-9]*$/', $var); 
+4
source

There are several ways to do this:

 /^[1-9][0-9]*$/ 

or

 /^(?!0)[0-9]+$/ 

Or one of them must be beautiful. The first should be more or less clear, and the second uses a negative statement with zero width to make sure the first digit isn 't 0.

Please note that the regular expression is not intended for numerical analysis. There are other ways to do this, which will be faster and more flexible in terms of number format. For instance:

 if (is_numeric($val) && $val != 0) 

... must take away any nonzero number, including decimals and scientific notation.

+2
source

You can solve this by making the first digit different from 0 with '/^[1-9][0-9]*$/'

With your list of examples:

 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 
+1
source

All Articles