Last active
July 18, 2017 11:01
-
-
Save legecha/359a39713d39a6e303f5b0647a918f06 to your computer and use it in GitHub Desktop.
UK Postcode Regex Improved
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 | |
| /** | |
| * Notes: | |
| * | |
| * - Adapted from Bulk_Data_Transfer_-_additional_validation_valid_from_12_November_2015.pdf provided by gov.uk | |
| * - We don't care about GIR 0AA seen in many other regexes | |
| * - We accept (like the original) there will be a few false positives | |
| * - Allows a single, optional space between left and right hand side | |
| * - Case insensitive | |
| * - Example below shows how to return uppercase with 1 space standard format | |
| * | |
| * To allow for nicer formatting when taking postcodes: | |
| * - Capturing group $1 is the left hand side | |
| * - Capturing group $2 is the right hand side | |
| * | |
| * Play around with it: https://3v4l.org/ju94t | |
| * Feel free to make suggestions! | |
| */ | |
| $regex = '/^((?:[A-Z][0-9]{1,2})|(?:(?:[A-Z][A-HJ-Y][0-9]{1,2})|(?:(?:[A-Z][0-9][A-Z])|(?:[A-Z][A-HJ-Y][0-9]?[A-Z])))) ?([0-9][A-Z]{2})$/i'; | |
| $testPostCodes = [ | |
| 'HU1 1EN', | |
| 'HU11EN', | |
| 'hu1 1en', | |
| 'hu11en', | |
| ]; | |
| foreach ($testPostCodes as $testPostCode) { | |
| $matches = []; | |
| if (!preg_match($regex, $testPostCode, $matches)) { | |
| throw new InvalidArgumentException("Invalid post code format"); | |
| } | |
| $postcode = strtoupper($matches[1] . ' ' . $matches[2]); | |
| echo "$testPostCode matches as $postcode\n"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment