将完整的美国街道地址解析为地址、城市、州、邮政编码


Parse Full USA Street Address into Address, City, State, Zip

我每次都有遵循这种格式的地址:

地址、城市、州邮编

示例:555 试驾,加利福尼亚州泰斯特维尔 98773

我想将地址解析为单独的变量:

  • 地址
  • 城市
  • 邮编

我尝试了一些preg_match示例,但它们不遵循与我使用的相同模式。是正则表达式还是我正在寻找preg_match?请帮忙!

如果您绝对肯定,则地址将始终像您的示例一样格式化,使用这些逗号,您有两个简单的选择。

选项 1:正则表达式

preg_match("/(.+), ('w+), ('w+) ('w+)/", $address, $matches);
list($original, $street, $city, $state, $zip) = $matches;

现在,您有了各自的地址变量。

工作示例:https://3v4l.org/veo0i

选项 2:分解

您还可以使用 explode() 将地址分成几块:

list($street, $city, $statezip) = explode(", ", $address);
list($state, $zip) = explode(" ", $statezip);

工作示例:https://3v4l.org/jrIjB

你可以想出sth。 比如:

(?P<address>[^,]+),'h+
(?P<city>[^,]+),'h+
(?P<state>'w+)'s+
(?P<zip>'w+)

查看有关 regex101.com 的演示。
PHP中,这将是:

$regex = '~
           (?P<address>[^,]+),'h+ # everything that is not a comma, followed by a comma and horizontal whitespace
           (?P<city>[^,]+),'h+    # the same as above 
           (?P<state>'w+)'h+      # word characters, followed by whitespace
           (?P<zip>'w+)
          ~x';                    # verbose mode
$string = '555 Test Drive, Testville, CA 98773';
preg_match($regex, $string, $match);
echo $match["address"]; 
# 555 Test Drive

在 ideone.com 上观看演示。
但是,如果逗号并不总是存在,这可能会变得非常混乱(请提供更多输入字符串)。

您也可以使用 explode()

$full_address = '555 Test Drive, Testville, CA 98773';
$address = explode(',', $full_address)[0];
$city = explode(',', $full_address)[1];
$state = explode(' ', trim(explode(',', $full_address)[2]))[0];
$zip = explode(' ', trim(explode(',', $full_address)[2]))[1];
echo $address.'<br>';
echo $city.'<br>';
echo $state.'<br>';
echo $zip;