PHP regular expression to validate Street address

I have the following PHP regular expression which seem to crash. I’m not an expert on regular expression and so I’m hoping someone here can help.

The regular expression is to validate street address and address only.

Example:
33-100 green st.
33-100 green street
100 green st
100 green street

function validateStreetAddress($street) {
      $addressPattern = "/\d+(\s+\w+){1,}\s+(?:st(?:\.|reet)?|dr(?:\.|ive)?|pl(?:\.|ace)?|ave(?:\.|nue)?|rd|road|lane|drive|way|court|plaza|square|run|parkway|point|pike|square|driveway|trace|park|terrace|blvd)?/";  
        if(preg_match($addressPattern, $treetA)) {    
          echo "Address matched!";               
      } else {       
          echo "Address not matched!";
      }
    } 

To me the glaring mistake is the variable input to the function named: $street then you use an undefined variable in the preg_match named: $treetA. The error message should have told you this.

1 Like

Are you sure that covers all possible addresses?

There is nothing more annoying than living at some address and then have a computer tell you that it doesn’t exist while it does. There is no fallback there, except for probably ordering stuff some place else.

In general, it’s best to just accept any text as an address.

5 Likes

If it’s just for one country only then the national postal operator for that country might offer a license for access to their address database, which submitted addresses could be checked and validated against

3 Likes

The Japanese Embassy in London would like a word about why their address isn’t valid.
Or the Gherkin. Or Anne Frank. or the Eiffel Tower?
How about any building on Broadway in New York?
Or anyone who lives in an apartment (30 green st. appt 109)?

1 Like

Or Scottish tenement addresses, typically something like:

3/2 44 Scotland Street

Hello Everybody,

Thank you for all of your inputs. After reading all of the feedback I decided to keep the street field open, sounds like its the best approach.

Thanks again everybody.
r

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.