Returns a true/false against a UK postcode, as well as attempting to format it correctly.
There are a million versions of this code on the internet, but being true to my FluffedVision roots and treating this as my notebook, rather than a traditional blog, I’m noting this snippet down here.
function isValidPostcode($originalPostcode) { $alpha1 = "[abcdefghijklmnoprstuwyz]"; $alpha2 = "[abcdefghklmnopqrstuvwxy]"; $alpha3 = "[abcdefghjkpmnrstuvwxy]"; $alpha4 = "[abehmnprvwxy]"; $alpha5 = "[abdefghjlnpqrstuwxyz]"; $pcexp[0] = '/^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/'; $pcexp[1] = '/^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/'; $pcexp[2] = '/^('.$alpha1.'{1}'.$alpha2.'{1}[0-9]{1}'.$alpha4.')([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/'; $pcexp[3] = '/^(gir)([[:space:]]{0,})(0aa)$/'; $pcexp[4] = '/^(bfpo)([[:space:]]{0,})([0-9]{1,4})$/'; $pcexp[5] = '/^(bfpo)([[:space:]]{0,})(c/o([[:space:]]{0,})[0-9]{1,3})$/'; $pcexp[6] = '/^([a-z]{4})([[:space:]]{0,})(1zz)$/'; $pcexp[7] = '/^ai-2640$/'; $postcode = strtolower($originalPostcode); $valid = FALSE; foreach ($pcexp as $regexp) { if (preg_match($regexp, $postcode, $matches)) { $postcode = strtoupper ($matches[1] . ' ' . $matches [3]); $postcode = preg_replace ('/C/O([[:space:]]{0,})/', 'c/o ', $postcode); preg_match($pcexp[7], strtolower($originalPostcode), $matches) AND $postcode = 'AI-2640'; $valid = TRUE; break; } } return $valid ? $postcode : FALSE; }
Usage:
if(isValidPostcode("thePostcodeToCheck")) { // postcode is valid } else { // postcode is not valid }