php extract UK postal code and validate it

十年热恋 提交于 2019-12-09 07:14:28

问题


I have some text blocks like

John+and+Co-Accountants-Hove-BN31GE-2959519

I need a function to extract the postcode "BN31GE". It may happen to not exist and have a text block without postcode so the function must also validate if the extracted text is valid postcode .

John+and+Co-Accountants-Hove-2959519

回答1:


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



回答2:


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.




回答3:


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})


来源:https://stackoverflow.com/questions/6409948/php-extract-uk-postal-code-and-validate-it

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