Jay
Jay

Reputation: 1104

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 guide (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!

Upvotes: 4

Views: 8929

Answers (4)

Lepidosteus
Lepidosteus

Reputation: 12027

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

Upvotes: 1

Justin Morgan
Justin Morgan

Reputation: 30715

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.

Upvotes: 2

meouw
meouw

Reputation: 42140

just check for a non zero digit first then any number of other digits

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

Upvotes: 4

NikiC
NikiC

Reputation: 101926

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

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

Upvotes: 16

Related Questions