0

I'm using this validator:

//validate postcode
function IsPostcode($postcode)
{
    $postcode = strtoupper(str_replace(' ','',$postcode));
    if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
    {
        return true;
    }
    else
    {
        return false;
    }
}

From this link.

But I want to be able to validate postcodes like ME20 and TN10 instead of a full blown ME20 4RN, TN0 4RN. This is the part of the postcode known as the 'outward code'.

Can someone help me out with the regex?

4

1 回答 1

2

你可以使用我更新的正则表达式来解决你的问题

它从我的角度来验证英国邮政编码

<?php 
function IsPostcode($postcode)
{
    $postcode = strtoupper(str_replace(' ','',$postcode));
    if(preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]?[\s]?[0-9][ABD-HJLNP-UW-Z]{2}$)/i",$postcode) || preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]$)/i",$postcode))
    {    
        return true;
    }
    else
    {
        return false;
    }
}

echo $result = IsPostcode('ME20');
?>

输出

1

希望这对你有帮助。

于 2013-07-31T09:47:40.077 回答