Created
January 23, 2015 14:46
-
-
Save davebarnwell/5937f13cc8eb3822c6b3 to your computer and use it in GitHub Desktop.
Clean and validate UK postcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Validate and parse UK post code | |
| * | |
| * @param string $postcode | |
| * @return array(["validate"] => TRUE/FALSE | |
| * ["prefix"] => first part of postcode | |
| * ["suffix"] => second part of postcode); | |
| */ | |
| function inspect_postcode($postcode) { | |
| $postcode = str_replace(' ', '', $postcode); // remove any spaces; | |
| $postcode = strtoupper($postcode); // force to uppercase; | |
| $valid_postcode_exp = "/^(([A-PR-UW-Z]{1}[A-IK-Y]?)([0-9]?[A-HJKS-UW]?[ABEHMNPRVWXY]?|[0-9]?[0-9]?))\s?([0-9]{1}[ABD-HJLNP-UW-Z]{2})$/i"; | |
| // set default output results (assuming invalid postcode): | |
| $output['validate'] = FALSE; | |
| $output['prefix'] = ''; | |
| $output['suffix'] = ''; | |
| if (preg_match($valid_postcode_exp, strtoupper($postcode))) { | |
| $output['validate'] = TRUE; | |
| $suffix = substr($postcode, -3); | |
| $prefix = str_replace($suffix, '', $postcode); | |
| $output['prefix'] = $prefix; | |
| $output['suffix'] = $suffix; | |
| } | |
| return $output; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment