Jump to content

Regular expression trouble


karmacrow

Recommended Posts

Hi, this should be an easy one but still somehow im not getting it.

 

I want to validate a zip code (a german one) which is made up of exactly 5 numbers.

 

So i use the following code

 

function fValidate_Postcode($postcode)
{
    if( ereg("[0-9]{5}", $postcode)===false )
    {
        return false;
    }
    return true;
}

 

but for some reason it returns true when the postcode is longer than 5 numbers. Why? I thought the {5} should make the regular expression only match if there are exactly 5 numbers?

 

Thanks for your help!

Link to comment
Share on other sites

<?php

if(! is_numeric($postcode){
echo"sorry your post code is not a number";
}

$x=strlen($postcode);

if($x >5){

echo"sorry your post code is more then 5 numbers long";

}elseif( ereg("^[0-9]{5}$", $postcode)){

//code here

}else{

echo"sorry your postcode is wrong";

}
?>

Link to comment
Share on other sites

but for some reason it returns true when the postcode is longer than 5 numbers. Why? I thought the {5} should make the regular expression only match if there are exactly 5 numbers?

The reason it doesn't work is that you are not declaring your string to match only those five digits. You are simply matching any string with five consecutive digits within it. So, yours would actually match something like "abc012345" as well as "09_23456zz?". To match the five and only the five digits, use something like this:

<?php
if (!preg_match('|^[\d]{5}\z|', $zip)) {
  // Your zipcode doesn't match!
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.