PHP regexp US address

可紊 提交于 2019-12-01 06:00:24

Ask the user to enter parts of the address in separate fields (Street name, City, State, and Zip Code) and use whatever validation appropriate for such a field. This is the general practice.

Alternatively, if you want simplest of regex that matches for four strings separated by three commas, try this:

/^(.+),([^,]+),([^,]+),([^,]+)$/

If things match, you can use additional pattern matching to check components of the address. There is no possible way to check the street address validity but you might be able to text postal codes and state codes.

Robert L

Don't try. Somebody is likely to have a post office box, or an apartment number etc., and they will be really irate with you. Even a "normal" street name can have numbers, like 125th Street (and many others) in New York City. Even a suburb can have some numbered streets.

And city names can have spaces.

There are way too many variations in address to be able to do this using regular expressions. You're better off finding a web service that can validate addresses. USPS has one - you'll have to request permission to use it.

rich

I agree with salman: have user enter the data in different fields (one for zip, one for state, one for city, and one for the #/street name. Use a different regex for each field. For the street #/name the best expression i came up with was

/^[0-9]{1,7} [a-zA-z0-9]{2,35}\a*/

This is not a bulletproof solution but the assumption is that an address begins with a numeric for the street number and ends with a zip code which can either be 5 or 9 numbers.

([0-9]{1,} [\s\S]*? [0-9]{5}(?:-[0-9]{4})?)

Like I said, it's not bulletproof, but I've used it with marginal success in the past.

Over here in New Zealand, you can license the official list of postal addresses from New Zealand Post - giving you the data needed to populate a table with every valid postal address in New Zealand.

Validating against this list is a whole lot easier than trying to come up with a Regex - and the accuracy is much much higher as well, as you end up with three cases:

  • The address you're validating is in the list, so you know it is a real address
  • The address you're validating is very similar to one in the list, so you know it is probably a real address
  • The address you're validating is not similar in the list, so it may or may not be real.

The best you'll get with a RegEx is

  • The address you're validating matches the regex, so it might be a real address
  • The address you're validating does not match the regex, so it might not be a real address

Needing to know postal addresses is a pretty common situation for many businesses, so I believe that licensing a list will be possible in most areas.

The only sticky bit will be pricing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!