Eyesis Home
  > Projects > PHP > Format Phone Number

PHP > Format Phone Number

Lets face it, visitors to our web sites are stupid (not you of course). People tend not to enter information correctly. This function will turn the poorly formatted phone numbers entered by users into a visually appealing set of numbers.

<?php
/**
 * FORMATPHONE
 * 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 ereg_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
?>