PHP: Formatting US Phone Numbers

You are here

Here's a simple function for formatting US phone numbers with 7 to 10 digits with possible extensions.

$phone = trim(stripslashes(strip_tags($_POST['phone'])));
$phone = preg_replace("/[^0-9]/", "", $phone);

// If the first Character in a phone number is 1, then strip it
if(substr($phone, 0, 1) == 1){
$phone = substr($phone, 1);
} else {
$phone = $phone;
}

// If the first Character in a phone number is 0, then strip it
if(substr($phone, 0, 1) == 0){
$phone = substr($phone, 1);
} else {
$phone = $phone;
}
// If the first Character in a phone number is 1, then strip it

if(strlen($phone) < 10){
$phone = '';
} elseif(strlen($phone) == 10) {
$phone = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3",$phone);
} elseif(strlen($phone) > 10){
// Only Keep the First 10 Characters of Phone Number
$phone = substr($phone, 0, 10);
// Only Keep the First 10 Characters of Phone Number
$phone = preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3",$phone);
} else {
$phone = '';
}

if($phone == "(000) 000-0000" || $phone == "(234) 567-8910" || $phone == "(456) 789-1011"){
redirect("http://www.yahoo.com"); // since they added an obviously bogus phone number, get them out of here
exit; // don't process anything else
}