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!

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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 />";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.