验证英国短(向外)邮政编码


Validate UK short (outward) postcode

我正在使用这个验证器:

//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;
    }
}

从此链接。

但我希望能够验证像ME20和TN10这样的邮政编码,而不是完整的ME20 4RN、TN0 4RN。这是邮政编码中被称为"向外代码"的部分。

有人能帮我处理正则表达式吗?

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

它在我这边工作,以验证英国邮政编码

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

希望这对你有帮助。