这是从一个数组我有PHP的正则表达式的城市国家邮编
[citystatezip] => New York, NY 50805-2578
我试图把它下面
[city] => New York
[state] => NY
[zip] => 50805-2578
格式我使用正则表达式中php..but得到无处。
感谢您的帮助。
这是从一个数组我有PHP的正则表达式的城市国家邮编
[citystatezip] => New York, NY 50805-2578
我试图把它下面
[city] => New York
[state] => NY
[zip] => 50805-2578
格式我使用正则表达式中php..but得到无处。
感谢您的帮助。
试试这个正则表达式:
/([^,]+),\s*(\w{2})\s*(\d{5}(?:-\d{4})?)/
翻译成代码:
$str = "New York, NY 50805-2578";
preg_match("/([^,]+),\s*(\w{2})\s*(\d{5}(?:-\d{4})?)/", $str, $matches);
list($arr['addr'], $arr['city'], $arr['state'], $arr['zip']) = $matches;
print_r($arr);
给出:
Array
(
[zip] => 50805-2578
[state] => NY
[city] => New York
[addr] => New York, NY 50805-2578
)
有了这个表达式:
有一些输入验证(例如:要求输入要在的形式:XXXXXXX,YY NNNNN-NNNN)
空白是可选
拉链的,最后4位是可选
(.+?), (\w+) ([-\d]+)
然后您可以通过捕获组的信息。
您需要在正则表达式中使用'ungreedy' /'?'。 – RobertPitt 2010-09-07 23:17:28
正则表达式的作品。我测试了它 – 2010-09-07 23:26:00
为什么不能做。
/(?P<city>[^,]+),\s*(?P<state>\w{2})\s*(?P<zip>\d{5}(?:-\d{4})?)/
节省你在干什么:
$arr['city'] = $matches[1];
$arr['state'] = $matches[2];
$arr['zip'] = $matches[3];
所以当你:
print_r($matches);
你会得到
Array
(
[city] => New York
[state] => NY
[zip] => 50805-2578
)
从
NullUserException
使用
主要表达和所有归功于他。我只是缩短了这个过程。
感谢man..work很好。 – andrewk 2010-09-07 23:26:57