Created
July 20, 2018 14:57
-
-
Save antom/90b7a6a72020424c2ea42a192cf7eefa to your computer and use it in GitHub Desktop.
PHP to build a UK telephone Regex Pattern from known formats.
This file contains 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 | |
// UK telephone formats (ref: http://www.area-codes.org.uk/formatting.php#programmers) | |
// prefix:chunks (eg. 434 -> 4444 333 4444) - # = any 0-9 digit | |
$formats = array( | |
'1:45', | |
'1:46', | |
'11:334', | |
'1#1:334', | |
'13873:55', | |
'15242:55', | |
'15394:55', | |
'15395:55', | |
'15396:55', | |
'16973:55', | |
'16974:55', | |
'16977:54', | |
'16977:55', | |
'17683:55', | |
'17684:55', | |
'17687:55', | |
'19467:55', | |
'2:244', | |
'3:334', | |
'5:46', | |
'500:36', | |
'7:433', | |
'800:36', | |
'8:334', | |
'9:334', | |
); | |
// known phone numbers that do not adhere to the formats defined above | |
$exceptions = array( | |
'800 ?1111', | |
'845 ?4647', | |
); | |
// compile a regex pattern for each area code format | |
$patterns = array(); | |
foreach($formats as $data) { | |
list($prefix,$format) = explode(':',$data,2); | |
// compile prefix regex with known digits | |
$format = str_split($format); | |
$format[0] = (int)$format[0] - strlen($prefix); | |
$prefix = str_replace('#','\d',$prefix) . ($format[0] > 0 ? sprintf('\d{%d}',$format[0]) : ''); | |
unset($format[0]); | |
// compile suffix regex for digits | |
$patterns[$data] = sprintf( | |
'%s ?\d{%s}', | |
$prefix, | |
implode('} ?\d{',$format) | |
); | |
} | |
echo '<pre>',print_r($patterns,1),PHP_EOL,PHP_EOL,implode('',array( | |
'/^(?:\+44 ?|0)(?:', | |
implode('|',array_merge($patterns,$exceptions)), | |
')$/' | |
)),'</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment