如何使用 php 仅收集邮政编码的前 1 或 2 个字符
How to collect just the first 1 or 2 characters of a postcode using php
我在 SO 上发现了这个有用的函数,但我需要它以稍微不同的方式工作。我必须只取邮政编码的前两个字符,不带任何数字,以便它们可用于与包含邮政编码前缀和区域的 table 进行比较。使用 CH7 搜索此数据库不会 return 任何结果,因为该数据库仅包含 CH。
function getUKPostcodeFirstPart($postcode)
{
// validate input parameters
$postcode = strtoupper($postcode);
// UK mainland / Channel Islands (simplified version, since we do not require to validate it)
if (preg_match('/^[A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?)\s*?\d[A-Z][A-Z]$/i', $postcode))
return preg_replace('/^([A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?))\s*?(\d[A-Z][A-Z])$/i', '', $postcode);
// British Forces
if (preg_match('/^(BFPO)\s*?(\d{1,4})$/i', $postcode))
return preg_replace('/^(BFPO)\s*?(\d{1,4})$/i', '', $postcode);
// overseas territories
if (preg_match('/^(ASCN|BBND|BIQQ|FIQQ|PCRN|SIQQ|STHL|TDCU|TKCA)\s*?(1ZZ)$/i', $postcode))
return preg_replace('/^([A-Z]{4})\s*?(1ZZ)$/i', '', $postcode);
// well ... even other form of postcode... return it as is
return $postcode;
}
如果我使用以下方法进行测试
$postcode ="CH7 3DT";
echo 'CH7 3DT -> ', getUKPostcodeFirstPart($postcode), "\n";
我得到了 CH7 的结果,这正是代码应该做的。但是我需要一个 return 的 CH
B31 5SN 应该 return 只是 B,
SY4 4RG 应该 return 只是 SY
我尝试删除 preg_replace 的各个部分以减少输出,但我要么一无所获,要么又得到完整的邮政编码。
老实说,preg_replace让我很困惑!
preg_replace("/[^A-Za-z]/", "", getUKPostcodeFirstPart($postcode));
这应该将所有非字母字符替换为空字符,实质上是将它们从字符串中删除。
我在 SO 上发现了这个有用的函数,但我需要它以稍微不同的方式工作。我必须只取邮政编码的前两个字符,不带任何数字,以便它们可用于与包含邮政编码前缀和区域的 table 进行比较。使用 CH7 搜索此数据库不会 return 任何结果,因为该数据库仅包含 CH。
function getUKPostcodeFirstPart($postcode)
{
// validate input parameters
$postcode = strtoupper($postcode);
// UK mainland / Channel Islands (simplified version, since we do not require to validate it)
if (preg_match('/^[A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?)\s*?\d[A-Z][A-Z]$/i', $postcode))
return preg_replace('/^([A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?))\s*?(\d[A-Z][A-Z])$/i', '', $postcode);
// British Forces
if (preg_match('/^(BFPO)\s*?(\d{1,4})$/i', $postcode))
return preg_replace('/^(BFPO)\s*?(\d{1,4})$/i', '', $postcode);
// overseas territories
if (preg_match('/^(ASCN|BBND|BIQQ|FIQQ|PCRN|SIQQ|STHL|TDCU|TKCA)\s*?(1ZZ)$/i', $postcode))
return preg_replace('/^([A-Z]{4})\s*?(1ZZ)$/i', '', $postcode);
// well ... even other form of postcode... return it as is
return $postcode;
}
如果我使用以下方法进行测试
$postcode ="CH7 3DT";
echo 'CH7 3DT -> ', getUKPostcodeFirstPart($postcode), "\n";
我得到了 CH7 的结果,这正是代码应该做的。但是我需要一个 return 的 CH
B31 5SN 应该 return 只是 B, SY4 4RG 应该 return 只是 SY
我尝试删除 preg_replace 的各个部分以减少输出,但我要么一无所获,要么又得到完整的邮政编码。 老实说,preg_replace让我很困惑!
preg_replace("/[^A-Za-z]/", "", getUKPostcodeFirstPart($postcode));
这应该将所有非字母字符替换为空字符,实质上是将它们从字符串中删除。