PHP: UK phone number formatter
<?php
/**
* Formats UK phone numbers.
*
* @param string $phone Phone number to format.
* @param bool $skype Whether to create a Skype link or not.
*
* @return string
*/
function format_phone($phone, $skype = FALSE)
{
// Strip out any existing spaces
$phone = str_replace(' ', '', $phone);
// Match 08xx xxx xxx
if (preg_match('/^08/', $phone))
{
$a = substr($phone, 0, 4);
$b = substr($phone, 4, 3);
$c = substr($phone, 7, 4);
}
// Match 011x xxx xxx
else if (preg_match('/^011/', $phone))
{
$a = substr($phone, 0, 4);
$b = substr($phone, 4, 3);
$c = substr($phone, 7, 4);
}
// Match 01x1 xxx xxx
else if (preg_match('/^01.1/', $phone))
{
$a = substr($phone, 0, 4);
$b = substr($phone, 4, 3);
$c = substr($phone, 7, 4);
}
// Match 02x xxxx xxxx
else if (preg_match('/^02./', $phone))
{
$a = substr($phone, 0, 3);
$b = substr($phone, 3, 4);
$c = substr($phone, 7, 4);
}
// Match 0xxxx xxx xxx
else
{
$a = substr($phone, 0, 5);
$b = substr($phone, 5, 3);
$c = substr($phone, 8, 3);
}
$phone = $a . ' ' . $b . ' ' . $c;
return $skype
? '<a href="callto:+44' . str_replace(' ', '', ltrim($phone, 0)) . '" title="Call this number using Skype" class="tooltip skype">' . $phone . '</a>'
: $phone;
}