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
https://forums.phpfreaks.com/topic/41980-regular-expression-trouble/
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";

}
?>

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!
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.