Forum Moderators: coopster

Message Too Old, No Replies

php regex numbers only

Trying to create a regular expression for PHP to accept digits only

         

WebSlug

2:50 pm on Jun 16, 2008 (gmt 0)

10+ Year Member



I'm trying to create a regular expression for PHP.

The entry must be numeric and contain 1 to 6 numbers.

e.g
1
324
343244

However when I test it using a & ampersand symbol it seems to think its numeric. Any ideas on how to work around this?

if (!preg_match("/^([0-9]{1,6})$/", $pageid) ¦¦ (is_numeric($pageid) != 1))
{
echo ("This is not a valid entry");
}

Any ideas?

Thanks in advance.

Receptional Andy

3:00 pm on Jun 16, 2008 (gmt 0)



I think it may be the way you're checking if the value is numeric. Try simply
!is_numeric($pageid)

Added: in fact, the second check shouldn't be necessary with the regex you have - they both achieve pretty much the same thing (although the regex has the added flexibility of checking length of the number), so I would only use one or the other.

[edited by: Receptional_Andy at 3:02 pm (utc) on June 16, 2008]

WebSlug

4:53 pm on Jun 16, 2008 (gmt 0)

10+ Year Member



Hi Andy! :D

I tried !isnumeric($pageid) and it didn't work with strings like

&*^&&( or &&&

Cheers anyway.

Receptional Andy

8:55 am on Jun 17, 2008 (gmt 0)



I tried !isnumeric($pageid) and it didn't work with strings like

&*^&&( or &&&

I'm not sure what you mean by "didn't work".

is_numeric
[php.net] checks if a value is numeric, so will return false for anything else. The exclamation mark checks if the return value is false, so
!is_numeric(121)
returns false and
!is_numeric('a£b3%7')
returns true.

As mentioned, I think the

is_numeric
check is unnecessary anyway, since if the regex works, you'll only ever get numbers, or you'll trigger the error.

dreamcatcher

10:28 am on Jun 17, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The ctype_functions [uk3.php.net] are more accurate. is_numeric won`t always return false if its not a digit. From the PHP website:

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

For digits use ctype_digit [uk3.php.net]. You can check the length of a string using strlen [uk3.php.net]

if (!ctype_digit($pageid) ¦¦ strlen($pageid)>6) {
return false;
}

You could also use the character classes:

if (!ereg("^[[:digit:]]+$", $pageid)) {
return false;
}

dc