Simple Regular Expression Problem

liunx

Guest
Using php I want to find out if a value entered in a form is 4 to 6 digits only.<br /><br />I used the expression<br /><br />if (!ereg("[0-9]{4,6})) die ("<h3 align=\"center\">The value you entered must be 4-6 digits only.<br />Use the back button and try again.</h3>");<br /><br />value - expected result - result<br />123 - fail - fail<br />1234 - pass - pass<br />123456 -pass -pass<br />1234567 - fail -PASS!!!!!<br /><br /><br />Why does this not work??? Any help would be appreciated.<!--content-->
The regex does not work as you as intend because as you have it, the regex will match on any <i>substring</i> of 4 to 6 digits. Besides allowing '1234567' to pass, values such as 'xyz1234' and '1234xyz' will also pass, because the test string <i>contains</i> a string of 4 to 6 digits.<br /><br />If you add "^" to the beginning of the regex (regex must match at beginning of string) and "$" to the end of the regex (regex must match at end of string), this will force the regex to match only on the entire string, rather than matching on a substring:<br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->if (!ereg("^[0-9]{4,6}$", $testvalue)) die ("<h3 align=\"center\">The value you entered must be 4-6 digits only.<br />Use the back button and try again.</h3>");<!--c2--></div><!--ec2--><!--content-->
David<br /><br />You know I went to a site, read the rules about 20 times and could not see why this was not working.<br />Read your post and you know...a light bulb went off in my head..of course.<br /><br />And of course it now works thanks to your reply, much appreciated!!<br /><br /><br />Wayne<!--content-->
 
Back
Top