从地址字符串中提取邮政编码

时间:2013-08-14 14:34:50

标签: php regex string

我想知道如何在地址字符串中查找邮政编码,并使用正则表达式将其变为自己的变量。

例如,

$address = '123 My Street, My Area, My City, AA11 1AA'

我想要$postcode = 'AA11 1AA'

我还想删除从地址字符串中找到的邮政编码。

到目前为止,我有这个。

$address = strtolower(preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $data[2]));

$postcode = 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",$address,$post);
$postcode = $post;

5 个答案:

答案 0 :(得分:3)

如果您想对此进行过度处理并处理所有可能的邮政编码变体,建议使用“官方”英国政府数据标准邮政编码正则表达式,如下所述:UK Postcode Regex (Comprehensive)。如下所示:

$postcodeRegex = "(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})";
if (preg_match($postcodeRegex, $address, $matches))
{
    $postcode = $matches[0];
}

(这给出了一般的想法,但正则表达式可能需要稍微调整,因为正则表达式的味道可能有所不同)。

答案 1 :(得分:2)

This worked for me:

$value = "Big Ben, Westminster, London, SW1A 0AA, UK";

$pattern = "/((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}))/i";

preg_match($pattern, $value, $matches);

$value = $matches[0]; // Will give you SW1A 0AA

http://www.sitepoint.com/community/t/extract-uk-postcode-from-string/31962

答案 2 :(得分:1)

您可以尝试按“,”拆分字符串。然后,邮政编码将是结果数组的最后一项(我不太了解PHP,但这是我的第一个,但你怎么能这样做。)

答案 3 :(得分:1)

这个正则表达式希望能帮到你

$address = '123 My Street, My Area, My City. AA11 1AA';

preg_match('/(.*)\.([^.]*)$/', $address, $matches);
$postcode = $matches[2];

### Output    
var_dump($matches);
array (size=3)
  0 => string '123 My Street, My Area, My City. AA11 1AA' (length=41)
  1 => string '123 My Street, My Area, My City' (length=31)
  2 => string ' AA11 1AA' (length=9)

答案 4 :(得分:1)

如果它始终按照您显示的顺序排列,则可以使用以下内容。我在第一组后面的(?=,)逗号使用positive look ahead断言,后跟一个文字逗号,。然后我在断言后面使用了一个逗号(?<=,),然后是一个潜在的(多个)空格字符\s*(我们没有在一个组中捕获),接着是其余的字符串中的字符。由于匹配时整个字符串必须为true,因此字符串仅与您指定的方式匹配(这就是为什么没有多个分组对)。

<?php
$address = "123 My Street, My Area, My City, AA11 1AA";
$splitter = "!(.*)(?=,),(?<=,)\s*(.*)!";
preg_match_all($splitter,$address,$matches);

print_r($matches);

$short_addr = $matches[1][0];
$postal_code = $matches[2][0];

?>

<强>输出

Array
(
    [0] => Array
        (
            [0] => 123 My Street, My Area, My City, AA11 1AA
        )

    [1] => Array
        (
            [0] => 123 My Street, My Area, My City
        )

    [2] => Array
        (
            [0] => AA11 1AA
        )

)