Skip to content

Instantly share code, notes, and snippets.

@codearmorygists
Created September 19, 2012 23:12
Show Gist options
  • Save codearmorygists/3752952 to your computer and use it in GitHub Desktop.
Save codearmorygists/3752952 to your computer and use it in GitHub Desktop.
Phone number beautifier
function format_phone($phone) {
$prefix = null;
//Check if number has international prefix
switch(true){
case substr($phone, 0, 1) == '+':
$phone = substr($phone, 1);
$prefix = '+';
break;
case substr($phone, 0, 2) == '00':
$phone = substr($phone, 2);
$prefix = '+';
break;
}
//Strip all non numeric characters
$phone = preg_replace("/[^0-9]/", '', $phone);
switch(strlen($phone)){
case 6:
return preg_replace("/([0-9]{2})([0-9]{2})([0-9]{2})/", "$1-$2-$3", $phone);
break;
case 7:
return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
break;
case 10:
return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
break;
case 11:
return preg_replace("/([0-9]{3})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
break;
case 12:
return preg_replace("/([0-9]{4})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
break;
default:
return $phone;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment