function format_uk_phone_number in Phone 5
Convert a valid United Kingdom phone number into standard +44 (0)1970 123 456 #001 international format
Parameters
$phonenumber must be a valid eleven-digit number (with optional extension):
File
- ./
phone.uk.inc, line 69
Code
function format_uk_phone_number($phonenumber) {
$area = $number = $extension = '';
//If we already have the formatting we want just return
if (preg_match("/\n (\n \\+44\\s\\(0\\)\\d{4}\\s\\d{3}\\s\\d{3} # 4 digit area code\n |\n \\+44\\s\\(0\\)\\d{3}\\s\\d{3}\\s\\d{4} # 3 digit area code\n |\n \\+44\\s\\(0\\)\\d{2}\\s\\d{4}\\s\\d{4} # 2 digit area code\n )\n (\\s\\#\\d*)?\n /", $phonenumber)) {
return $phonenumber;
}
else {
//Simplify to 10 digit number and clean up ready for international reformat.
$phonenumber = preg_replace("/^(\\+44)?\\s?(\\(?0\\)?)?/", "", $phonenumber);
$phonenumber = preg_replace("/\\(/", "", $phonenumber);
$phonenumber = preg_replace("/\\(0/", "", $phonenumber);
$phonenumber = preg_replace("/\\)/", "", $phonenumber);
//If there are some spaces in the number assume some level of preformatting
if (preg_match("/ /", $phonenumber)) {
$regex = "/\n # 4 digit area code.\n (\n (\\d{4}) # capture 4 digit area code\n \\s+ # ignore required separator to make a distinction with other area codes\n (\\d{3}) # capture first set of numbers in the local number\n \\s* # ignore optional separator\n (\\d{3}) # capture second set of numbers in the local number\n |\n # 3 digit area code.\n (\\d{3}) # capture 3 digit area code\n \\s+ # ignore required seperator\n (\\d{3}) # capture first set of numbers in the local number\n \\s* # ignore possible boundary\n (\\d{4}) # capture second set of numbers in the local number\n |\n # 2 digit area code.\n (\\d{2}) # capture 2 digit area code\n \\s+ # ignore required boundary to make a distinction with other area codes\n (\\d{4}) # capture first set of numbers in the local number\n \\s* # ignore possible boundary\n (\\d{4}) # capture second set of numbers in the local number\n )\n # capture the optional extension number\n (\\s*\\#)?\n (\\d{4}|\\d{3})?\n /x";
preg_match($regex, $phonenumber, $matches);
var_export($matches);
$area = $matches[2] . $matches[5] . $matches[8];
$number = $matches[3] . $matches[6] . $matches[9] . ' ' . $matches[4] . $matches[7] . $matches[10];
$extension = $matches[12];
}
else {
preg_match("/(\\d{4})(\\d{3})(\\d{3})\\#?(\\d*)?/", $phonenumber, $matches);
$area = $matches[1];
$number = $matches[2] . ' ' . $matches[3];
$extension = $matches[4];
}
$phonenumber = '+44 (0)' . $area . ' ' . $number;
$phonenumber .= empty($extension) ? '' : " #{$extension}";
}
return $phonenumber;
}