A function to check if a UK postcode is valid, but also returns a correctly formatted version.
function formatBritishPostcode($postcode) {
//--------------------------------------------------
// Clean up the user input
$postcode = strtoupper($postcode);
$postcode = preg_replace('/[^A-Z0-9]/', '', $postcode);
$postcode = preg_replace('/([A-Z0-9]{3})$/', ' \1', $postcode);
$postcode = trim($postcode);
//--------------------------------------------------
// Check that the submitted value is a valid
// British postcode: AN NAA | ANN NAA | AAN NAA |
// AANN NAA | ANA NAA | AANA NAA
if (preg_match('/^[a-z](\d[a-z\d]?|[a-z]\d[a-z\d]?) \d[a-z]{2}$/i', $postcode)) {
return $postcode;
} else {
return NULL;
}
}
And for an example of its usage...
$postCodeClean = formatBritishPostcode('b s 165 rh');
if ($postCodeClean === NULL) {
exit('This does not appear to be a valid postcode');
} else {
exit($postCodeClean);
}
In the above example, the output would be "BS16 5RH"
Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.