Simple Phone Number Format Function

Dec 06

This simple function will turn the poorly formatted phone numbers entered by users into a visually appealing set of numbers.

/**
* Converts phone numbers to the formatting standard
*
* @param   String   $num   A unformatted phone number
* @return  String   Returns the formatted phone number
*/
function formatPhone($num)
{
$num = preg_replace('/[^0-9]/', '', $num);

$len = strlen($num);
if($len == 7)
$num = preg_replace('/([0-9]{3})([0-9]{4})/', '$1-$2', $num);
elseif($len == 10)
$num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', '($1) $2-$3', $num);

return $num;
}

// echo formatPhone('1 208 - 386 2934');
// will print: (208) 386-2934 </code>