I need to match using regular expression in php addresses like:
- 144 street, city, state zip/postal code
- 144 street, apt #1, city, state zip/postal code
- 144 street apt #1, city state zip/postal code
The zip/postal code can includes letters and/or numbers.
Here’s what I tried:
print_r(preg_match('/^([0-9]+)\s([a-z]+)\s([a-z]+)\s([a-z]+)\s([a-z0-9]+)$/i', $t, $m));
print_r($m);
it outputs:
Array
(
[0] => 123 asd asd asd 123
[1] => 123
[2] => street
[3] => city
[4] => state
[5] => zip
)
This works using spaces only. When I have a comma it does not work and it result in an empty array.
What can I do to also includes commas?
Why not simply remove the comma and then use your regular expression?
Also for alphanumeric zip you might need to add other characters than
a-z0-9since Canadian zip codes use space.The other thing you will need to check is if a street has spaces in it like:
OR
Your regular expression will not work. Same for City.
Using an API is good but you have to get the API for the countries you need. If you want to validate All of the country that can be painful.
ceejayoz has a good answer, but what I think you should do is get the API for the top countries you get and then use the regex for everything else.