如果您使用正则表达式来匹配英国邮政编码(部分或全部),那么您做错了。另外,在继续之前请注意,无论您如何编写代码,都有一种情况会导致格式不明确:BS22 很可能属于 BS2 2AB 或 BS22 5GS。绝对没有办法告诉你,你需要根据它做出决定。
我建议的算法将 BS22 的情况视为 BS22。如下:
<?php
function testPostcode($mypostcode) {
if (($posOfSpace = stripos($mypostcode," ")) !== false) return substr($mypostcode,0,$posOfSpace);
// Deal with the format BS000
if (strlen($mypostcode) < 5) return $mypostcode;
$shortened = substr($mypostcode,0,5);
if ((string)(int)substr($shortened,4,1) === (string)substr($shortened,4,1)) {
// BS000. Strip one and return
return substr($shortened,0,4);
}
else {
if ((string)(int)substr($shortened,3,1) === (string)substr($shortened,3,1)) {
return substr($shortened,0,3);
}
else return substr($shortened,0,2);
}
}
// Test cases
$postcodes = array("BS3 3PL", "BS28BS","BS34","BS345","BS32EQ");
foreach ($postcodes as $k => $v) {
echo "<p>".$v." => ".testPostcode($v)."</p>";
}
这比正则表达式维护起来更快更简单。