php extract UK postal code and validate it

核能气质少年 提交于 2019-12-03 09:13:58

Find below code to extract valid UK postal code. It return array if post code found otherwise empty.

<?php
$getPostcode="";
$str="John+and+Co-Accountants-Hove-BN31GE-2959519";
$getArray = explode("-",$str);
if(is_array($getArray) && count($getArray)>0) {
    foreach($getArray as $key=>$val) {
        if(preg_match("/^(([A-PR-UW-Z]{1}[A-IK-Y]?)([0-9]?[A-HJKS-UW]?[ABEHMNPRVWXY]?|[0-9]?[0-9]?))\s?([0-9]{1}[ABD-HJLNP-UW-Z]{2})$/i",strtoupper($val),$postcode)) {
            $getPostcode = $postcode[0];
        }
    }
}
print"<pre>";
print_r($getPostcode); 
?>

The UK Government Data Standard for postcodes is:

((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))

Edit: I had the above in some (personal) code with a reference to a now non-existence UK government web page. The appropriate British Standard is BS7666 and information on this is currently available here. That lists a slightly different regex.

Use a regex: preg_grep function,

I don't know the format of english postcodes but you could go with something like:

(-[a-zA-Z0-9]+-)+

This matches

  • "-Accountants-"
  • "-BN31GE-"

You can then proceed at taking always the second value or you can enhance you regex to match exactly english postcodes, something like maybe

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