Search code examples
phpregexyiistreet-address

Street Address Validation with PHP


I need to validate a complete address using php and regex. This is what i have created so far.

<?php

$input = '15 Gordon St, 3121 Cremorne, Australia';
if (!preg_match('/^[^@]{1,63}@[^@]{1,255}$/', $input)) {
    echo 'Not matched';
} else {
    echo 'Matched';
}

sample Address.

15 Gordon St, 3121 Cremorne, Australia

This is returning false.

#, Street name, Zip Code, City, Country is the address format.


Solution

  • Your regex looks very much like an email-address validation one, which strongly suggests you don't know regex at all.
    I'm not even gonna argue that this is a "gimme teh codez" question anymore, but honestly, you should learn regex if you intend to use it.

    \d+ = one or more digits
    [a-zA-Z ]+ = one or more of: upper case letter, lower case letter, space

    Therefore:

    preg_match('/^\\d+ [a-zA-Z ]+, \\d+ [a-zA-Z ]+, [a-zA-Z ]+$/', $input)
    

    Which could also be shortened to:

    preg_match('/^(?:\\d+ [a-zA-Z ]+, ){2}[a-zA-Z ]+$/', $input)