Search code examples
phpregexpreg-match

Parse Full USA Street Address into Address, City, State, Zip


I have addresses that follow this format every time:

Address, City, State Zip

Example: 555 Test Drive, Testville, CA 98773

I would like to parse the address into separate variables for:

  • Address
  • City
  • State
  • Zip

I have tried some preg_match examples but they don't follow the same pattern I am using. Is it regex or preg_match im looking for? Please help!


Solution

  • If you are absolutely positive the addresses will always be formatted just like your example, with those commas, you have two simple options.

    Option 1: Regex

    preg_match("/(.+), (\w+), (\w+) (\w+)/", $address, $matches);
    list($original, $street, $city, $state, $zip) = $matches;
    

    Now you have your individual address variables.

    Working example: https://3v4l.org/veo0i

    Option 2: Explode

    You can also use explode() to pull apart the address into pieces:

    list($street, $city, $statezip) = explode(", ", $address);
    list($state, $zip) = explode(" ", $statezip);
    

    Working example: https://3v4l.org/jrIjB