php extract UK postal code and validate it

前端 未结 3 1633
误落风尘
误落风尘 2021-02-11 08:09

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

相关标签:
3条回答
  • 2021-02-11 08:31

    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 讨论(0)
  • 2021-02-11 08:40

    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.

    0 讨论(0)
  • 2021-02-11 08:43

    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); 
    ?>
    
    0 讨论(0)
提交回复
热议问题