开发者

php extract UK postal code and validate it

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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜