我每次都有遵循此格式的地址:
地址,城市,州邮编
示例:555 Test Drive,Testville,CA 98773
我想将地址解析为单独的变量:
我尝试了一些preg_match示例,但它们并没有遵循我使用的相同模式。是正在寻找正则表达式还是preg_match?请帮忙!
答案 0 :(得分:6)
如果您是绝对肯定的,地址将始终像您的示例一样格式化,使用这些逗号,您有两个简单的选项。
preg_match("/(.+), (\w+), (\w+) (\w+)/", $address, $matches);
list($original, $street, $city, $state, $zip) = $matches;
现在你有了自己的地址变量。
您还可以使用explode()
将地址分成几部分:
list($street, $city, $statezip) = explode(", ", $address);
list($state, $zip) = explode(" ", $statezip);
答案 1 :(得分:0)
你可以拿出某事。像:
(?P<address>[^,]+),\h+
(?P<city>[^,]+),\h+
(?P<state>\w+)\s+
(?P<zip>\w+)
请参阅a demo on 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
请参阅a demo on ideone.com 但是,如果逗号并不总是存在,则会变得非常混乱(请提供更多输入字符串)。
答案 2 :(得分:0)
您还可以使用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;