开发者

php regex city state zip

this is from an array i have

 [citystatezip] => New York, NY 50805-2578

i'm trying to have it in the format below

[city] => New York
[state]开发者_开发问答 => NY
[zip] => 50805-2578

i was using regex in php..but got nowhere.

thanks for the help.


Try this regex:

/([^,]+),\s*(\w{2})\s*(\d{5}(?:-\d{4})?)/

Translated into code:

$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);

Gives:

Array
(
    [zip] => 50805-2578
    [state] => NY
    [city] => New York
    [addr] => New York, NY 50805-2578
)

With this regex:

  • There is some input validation (eg: requires input to be in the form of: XXXXXXX, YY NNNNN-NNNN)

  • Spaces are optional

  • The last 4 digits of the zip are optional


(.+?), (\w+) ([-\d]+)

Then get the info from the capturing groups.


Why not do.

/(?P<city>[^,]+),\s*(?P<state>\w{2})\s*(?P<zip>\d{5}(?:-\d{4})?)/

Saves you doing:

$arr['city'] = $matches[1];
$arr['state'] = $matches[2];
$arr['zip'] = $matches[3];

so when you:

print_r($matches);

you will get

Array
(
    [city] => New York
    [state] => NY
    [zip] => 50805-2578
)

Main expression used from NullUserException and all credit goes to him. I just shortened the process.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜