tags:

views:

40

answers:

1
+2  Q: 

php regex issues

I have a pattern match here that looks like it should work fine. However any input I give makes the conditional fail. I will handle the '99999-9999' case after I get the '99999' case working.

$ZipCode is a textfield that is being submitted on POST.

$ZipCode                        = $_POST["ZipCode"];

if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{$error_str .= "The zip code you enter must be in the form of: '99999' or '99999-9999'\n";}

if(isset($_POST['submit']))
{?><script>var error = <?= json_encode($error_str);?>;
   alert(error);
  </script>
<?}

'11111' fails and '111111' also fails

+2  A: 

Your code should work correctly. Example:

$ZipCode = "111111";

if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{
    echo "Incorrect format";
}

Result:

Incorrect format

Try entering some invalid input to see if the error message is displayed.


To handle both cases at once you can use this regular expression:

/^[0-9]{5}(?:-[0-9]{4})?$/
Mark Byers
I tried that already, but it still fails.
Speedyshady
There must be an error with the content of your `$ZipCode` variable
Colin Hebert
Colin HERBERT's approach is a good suggestion so +1 for that, but it's not the only possible error. Another is that you might be modifying the file but forgetting to save it. It happens a lot... it's an easy mistake to make.
Mark Byers
Slipped my mind.
Speedyshady
Or you might be modifying a different file from the one you are running.
Mark Byers
Edited code again. Maybe this will provide more clarification.
Speedyshady
Did you try to echo your variable before doing the regex check ?
Colin Hebert
When I set $ZipCode = 11111 and echo $ZipCode, it prints 455. This must be the problem.
Speedyshady
The issue was in the html. Thanks for the help.
Speedyshady
Sorry about question but what means ?: in parentheses?
Centurion
@Centurion: It makes the parentheses non-capturing. See http://www.regular-expressions.info/brackets.html for more information.
Mark Byers
@ Mark Byers, Thanks.
Centurion