开发者

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']))
{?><sc开发者_JS百科ript>var error = <?= json_encode($error_str);?>;
   alert(error);
  </script>
<?}

'11111' fails and '111111' also fails


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})?$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜