Reputation: 157
I am trying to figure out the reg ex to match a street address. The format of the street address must be 2 or 3 digit number followed by a text string of the street name then ending with "Street" or "Road".
So a valid address can be:
Invalid address would be:
preg_match("/^[0-9]{2,3} *[a-zA-Z] *(Street|Road)$/", $_POST['street'])
I've tried multiple ways to approach this and can't get the digits in to work correctly.
If I try /^[0-9]{2,3}$/
it works by itself but when I add in the string expressions, it messes it up. Also using that formula without ^ or $, it'll validate any amount of digits beyond 3 digits long. So 1234, 12345, etc will work.
Upvotes: 3
Views: 4845
Reputation: 785108
You don't have correct regex to match street name that comes after first digits since [a-zA-Z]
will match single alphabet only
Use this regex:
preg_match("/^[0-9]{2,3} +[a-zA-Z]+ +(Street|Road)$/", $_POST['street']);
Difference is [a-zA-Z]+
instead of [a-zA-Z]
PS: Also changes to +
instead of *
since at least 1 space is needed between these components.
Upvotes: 1