Click to See Complete Forum and Search --> : Parse city, state and zip (when on one line)


sfullman
05-08-2008, 10:04 PM
here is some code that was handy for me to find the city, state, and zip code + 4 - also will find Canadian zip codes if you wish to mail to canadians :) just kidding



function parse_citystatezip($address){
/***
2008-05-08 used first for quickbooks import => database table

johnson city, tex|tx|texas 78691[-1234]
vancouver, bc A0A 0A0
charlotte, n.c. 02899

***/
$address=trim($address);
$zip='([a-z0-9][0-9][a-z0-9][- ]*[0-9][a-z0-9][0-9]*)([- ]+([0-9]{4}))*';
$state='([.a-z]{2,4})';
if(!preg_match("/\s+$state\s+$zip".'$'."/i",$address,$a))return false;
$state=strtoupper(str_replace('.','',$a[1]));
$zip=$a[2];
if($plus4=$a[4])$zipplus4=$zip.'-'.$plus4;
$city=substr($address,0,strlen($address)-strlen($a[0]));
$city=rtrim($city,',');
$order=array(
'city',
'state',
'zip',
'plus4',
'zipplus4'
);
foreach($order as $v){
echo $v . '<br>
';
isset($$v)?$b[$v]=$$v:'';
}
return $b;
}
echo '<pre>';
print_r(parse_citystatezip($addr));

PartDigital
07-04-2008, 11:24 AM
nice job, good use of regular expressions.

nrg_alpha
07-04-2008, 01:06 PM
I was just wondering.. when you are using a regular expression to check the format of a zip code, would you not want to include the carrot (^) to start the expression and use the $ at the end?

Currently, you have:


$zip='([a-z0-9][0-9][a-z0-9][- ]*[0-9][a-z0-9][0-9]*)([- ]+([0-9]{4}))*';


Would it not be better to use? :


$zip='(^[a-z0-9][0-9][a-z0-9][- ]*[0-9][a-z0-9][0-9]*)([- ]+([0-9]{4}))*$';


I could be wrong.. but doesn't the current code mean someone can add characters before / after the conditions set and go by undetected?

One other thing to note... in this line:


if($plus4=$a[4])$zipplus4=$zip.'-'.$plus4;


Are you checking if the variable $plus4 is equal to $a[4]?
Because with this line, you are indeed assigning $plus4 to equal $a[4] (which will always result in being true.
otherwise, it should be:


if($plus4 == $a[4]) $zipplus4 = $zip.'-'.$plus4;


Lasty, this looks incorrect:

isset($$v)?$b[$v]=$$v:'';


You have a few dollar signs too many I think ;)

Cheers,

NRG

bradgrafelman
07-04-2008, 01:17 PM
You have a few dollar signs too many I thinkActually, he has just the right amount - he's using variable variables.

nrg_alpha
07-04-2008, 01:31 PM
Actually, he has just the right amount - he's using variable variables.

I stand corrected..
http://www.phpbuilder.com/manual/en/language.variables.variable.php

Didn't realise he was going for variable variables. My bad.

Cheers,

NRG