Skip to content

Instantly share code, notes, and snippets.

@legecha
Last active July 18, 2017 11:01
Show Gist options
  • Select an option

  • Save legecha/359a39713d39a6e303f5b0647a918f06 to your computer and use it in GitHub Desktop.

Select an option

Save legecha/359a39713d39a6e303f5b0647a918f06 to your computer and use it in GitHub Desktop.
UK Postcode Regex Improved
<?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