tags:

views:

188

answers:

2

Hi, I'm using ereg in the followin way to validate a field which can contain only numbers from 0 to 9:

if(eregi("^([0-9])*$", $mynumber)) return true;

However the string must have between 8 and 10 characeters. Is it possible to improve the same ereg usage to check for a valid string length as well?

Thanks in advance.. all ereg tutorials seem to be traditional chinese to me. :S

+1  A: 

Just replace the * quantifier with {8,10}:

eregi("^[0-9]{8,10}$", $mynumber)

Now the regular expression only matches if the string consists of 8 to 10 digits.

And, by the way: The i in eregi is for case-insensitivity. But digits have no case. So you could use ereg instead. But since the use of PHP’s POSIX ERE functions is deprecated in favor to PHP’s PCRE functions, you should use preg_match instead:

preg_match("/^[0-9]{8,10}$/", $mynumber)
Gumbo
Thanks, that was very useful. ;)
Andrew
+3  A: 

ereg*() functions are deprecated, and will be removed in a future version:

if(preg_match("/^([0-9]){8,10}$/", $mynumber)) return true;
Ignacio Vazquez-Abrams