从地址字符串中提取邮政编码 [英] Extracting a zip code from an address string

查看:137
本文介绍了从地址字符串中提取邮政编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些完整的地址,例如:

I have some full addresses, for example:

$addr1 = "5285 KEYES DR  KALAMAZOO MI 49004 2613"
$addr2 = "PO BOX 35  COLFAX LA 71417 35"
$addr3 = "64938 MAGNOLIA LN APT B PINEVILLE LA 71360-9781"

我需要从字符串中取出5位邮政编码.我怎样才能做到这一点?也许使用RegEx?

I need to get the 5-digit zip code out of the string. How can I do that? Perhaps with RegEx?

一个可接受的答案是假设一个地址中可以有多个5位数字,但是邮政编码始终是最后一个连续的5位数字.

An acceptable answer assumes that there could be multiple 5-digit numbers in an address, but the Zip code will always be the last consecutive 5 digit number.

我的想法是使用explode然后遍历并检查每个索引.有人有更好的主意吗?

My idea was to use explode then loop through and check each index. Anyone got a better idea?

非常感谢您的帮助.

推荐答案

谈到美国邮政编码,为了获得邮政编码,这些邮政编码先跟两个字母状态代码,您可以使用以下正则表达式:

Speaking about US zip-codes, which are pre-followed with two letter state code in order to get a zip-code you could use the following regex:

/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/

说明:

\b         # word boundary
[A-Z]{2}   # two letter state code
\s+        # whitespace
\d{5}      # five digit zip
(-\d{4})?  # optional zip extension
\b         # word boundary

在线示例

$addr1 = "5285 KEYES DR  KALAMAZOO MI 49004 2613";
$addr2 = "PO BOX 35  COLFAX LA 71417 35";
$addr3 = "64938 MAGNOLIA LN APT B PINEVILLE LA 71360-9781";

function extract_zipcode($address) {
    $zipcode = preg_match("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $address, $matches);
    return $matches[0];
}

echo extract_zipcode($addr1); // MI 49004
echo extract_zipcode($addr2); // LA 71417
echo extract_zipcode($addr3); // LA 71360-9781

在线示例

为了扩展功能和灵活性,您可以指定是否要保留状态代码:

In order to extend functionality and flexibility, you can specify if you wish to keep state code or not:

function extract_zipcode($address, $remove_statecode = false) {
    $zipcode = preg_match("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $address, $matches);
    return $remove_statecode ? preg_replace("/[^\d\-]/", "", extract_zipcode($matches[0])) : $matches[0];
}
 
    echo extract_zipcode($addr1, 1); // 49004 (without state code)
    echo extract_zipcode($addr2);    // LA 71417 (with state code)
 

在线示例

这篇关于从地址字符串中提取邮政编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆