Search code examples
phppreg-match

PHP mailing address preg_match() not working


I am trying to make a regular expression to match this mailing address:

4F 50 Adele Street 01234 London

Here is my code:

if( !(preg_match('/[1-9]{5}[A-Za-z] [1-9] [A-Za-z\.]+ [A-Za-z\.]+ [0-9]{5} [A-Za-z\.]+/', $address))){
        return true;
    }
}

Solution

  • Try this RE:

    /[1-9][a-z] [1-9][0-9] [a-z.]+ [a-z.]+ [0-9]{5} [a-z.]+/i
    

    Changes:

    • There's only 1 digit at the beginning, I removed {5}
    • The second number has 2 digits, I changed [1-9] to [1-9][0-9]
    • You don't have to escape . inside brackets
    • Instead of A-Za-z, I just write a-z and use the i modifier to make it case insensitive

    DEMO