Jump to content

How do I capture data from a long address (complex)?


Re321

Recommended Posts

An example of the address is: 494 Main, Brook, MA, 19076. I've tried many regular expressions but I just can't do it, The street name can be any length but the state abbreviation can only be 2 or 3 characters long, The zip code is 5 ({5}?)

 

I've wrote the first part, something like ((\d+)\s+(\w+)),\s+(\w+) .. But I don't know what to do for the rest, I really need help!

The rest isn't too hard, Here:

"/((\d+)\s+(\w+)),\s+(\w+),\s+([A-Z]{2,3}),\s+(\d{5})/"

 

Note the ranges, so it will conform to your length rules.

 

Thanks oni for your fast reply.

 

How would I use this to echo all matches? I simplty need it on one address, I may loop it through addresses later but I need to list the captured data if it's right!

It's simple, Matches are stored in an array; so you could do this.

$address = "494 Main, Brook, NC, 19076";

$valid = "/((\d+)\s+(\w+)),\s+(\w+),\s+([A-Z]{2,5}),\s+(\d{5})/";

if ( preg_match( $valid, $address, $matches ) == 1 ) {
print "Street: ${matches[1]}<br />";
print "Street number: ${matches[2]}<br />";
print "Street name: ${matches[3]}<br />";
print "City: ${matches[4]}<br />";
print "State: ${matches[5]}<br />";
print "Zip: ${matches[6]}<br />";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.