My regex knowledge isn't the best and although I've been looking through posts to get my head around it I'm unable to find what I'm looking for.
I would like to use the following (where $postcode is the full postcode entered by the user):
if(preg_match("AREA CODE REGEX GOES HERE", $postcode))
{
//Do something
}
to do the following:
Check where postcode area code entered matches one of the following DN15,16,17,18,19,20,21,22,31,32,33,34,35,36,37,38,39,40,41 (all DN).
So I'm looking for the regex to match only those postcodes. It could be DN21 1AB or DN21 2AB for example but it has to match the first part still of DN21.
I hope that's enough information and thanks in advance for the help.
Try this regex pattern, provided by the British Government itself:
(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})
So to apply it to your situation, you can first check that you're dealing with a valid UK post code, and then check if the first part starts with 'DN' and the second part is any one of the ranges in the accepted-numbers array:
$accepted_numbers = array_merge(range(15, 22), range(31, 41));
if (preg_match('#^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$#', $postcode) && substr($postcode, 0, 2) == 'DN' && in_array(substr($postcode, 2, 2), $accepted_numbers)) {
// The UK post code is valid according to your criteria
}
Source: http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/254290/GDS%20Catalogue%20Vol%202.pdf (page 11)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With