<?php
$arr_postcode_regexes = array(
'uk' => array( // Should match any *valid* UK postcode
array('[A-Z]', '[A-Z]?', '[0-9]', '[0-9A-Z]?'),
),
'offshore' => array( // All postcode areas that DPD define as "offshore"
array('A', 'B', '3', '[0-8]'), // AB30-38
array('A', 'B', '4', '[1-9]'), // AB41-49
array('A', 'B', '5', '[0-6]'), // AB50-56
array('F', 'K', '1', '[789]'), // FK17-19
array('F', 'K', '2', '[01]'), // FK20-21
array('G', '8', '3'), // G83
array('G', 'Y', '9'), // GY9
array('H', 'S', '[1-9]'), // HS1-9
array('I', 'M', '[0-9]', '[0-9A-Z]?'), // IM
array('I', 'M', '[0-9]', '[0-9A-Z]?'), // IV
array('K', 'A', '2', '[89]'), // KA27-28
array('K', 'W', '[0-9]', '[0-9]?'), // KW0-99
array('P', 'A', '[2-9]', '[0-9]'), // PA20-99
array('P', 'H', '1', '[5-9]'), // PH15-19
array('P', 'H', '[2-9]', '[0-9]'), // PH20-99
array('T', 'R', '2', '[1-5]'), // TR21-25
array('Z', 'E', '[0-9]', '[0-9A-Z]?'), // ZE
),
'ni' => array( // Northern Ireland
array('B', 'T', '[0-9]', '[0-9A-Z]?'), // ZE
),
);
// Turn the readable-ish map above into actual regexes
// It's important that all regexes match only full, valid postcodes, as prefix matching can be ambiguous.
// Pack everything out with \s* because people are idiots and put whitespace in weird places.
foreach ($arr_postcode_regexes as $str_id => $arr_parts) {
$arr_temp = array();
foreach ($arr_parts as $arr_part) {
$arr_temp[] = implode('\s*', $arr_part) . '\s*[0-9]\s*[A-Z]\s*[A-Z]';
}
$arr_postcode_regexes[$str_id] = '^\s*(' . implode('|', $arr_temp) . ')\s*$';
}
var_dump($arr_postcode_regexes);
preferences:
36.33 ms | 402 KiB | 5 Q