Validate UK short postcode

谁说我不能喝 提交于 2020-01-30 13:15:09

问题


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.

Can someone help me out with the regex?


回答1:


you can use my updated regex to solve you problem

it working from my end to validate UK zip code

<?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');
?>

OUTPUT

1

Hope this will sure help you.



来源:https://stackoverflow.com/questions/17966788/validate-uk-short-postcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!