Search code examples
phpregexpostal-code

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

Solution

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