
Originally Posted by
mastap
postal code should always have a letter at the start and end e.g NE7 7BB. With a space between
The UK postal code system is not that simple. The format of UK postcodes is generally:- LD DLL
- LLD DLL
- LDD DLL
- LLDD DLL
- LLDL DLL
- LDL DLL
- where L signifies a letter and D a digit.
There is only one UK mainland postcode that breaks the above syntax rules: GIR 0AA which is the postcode of the, formerly Post Office owned, National Girobank.
You should not check for the space because some people will omit it. The following will check the postcode complies with that syntax and if it does it will format it upper case with the space ready to use:
PHP Code:
<?php
$postcode = 'SW1A 2AA'; # 10 downing street
if((preg_match('@^([A-Z]{1,2}[0-9]{1,2}[a-z]?) ?([0-9][ABDEFGHJLNPQRSTUWXYZ]{2})$@i', $postcode, $matches)) and ($postcode = strtoupper($matches[1].' '.$matches[2])))
{
# valid
}
else
{
# invalid
}
?>
Bookmarks