tags:

views:

52

answers:

3

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.

A: 

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

NullUserException
thanks man..works nicely.
andrewk
A: 

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

Then get the info from the capturing groups.

SimpleCoder
you need to use the `ungreedy` / `?` in your regex.
RobertPitt
The Regex works. I tested it
SimpleCoder
A: 

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.

RobertPitt