douqi1928 2011-06-20 10:40
浏览 106
已采纳

php提取英国邮政编码并验证它

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
  • 写回答

3条回答 默认 最新

  • dongtong1226 2011-06-20 11:31
    关注

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

报告相同问题?