Format Phone Numbers with PHP
Using PHP, this little bit of code parses and formats numbers by putting parentheses and a hyphen into the phone number. This code handles 10 digit phone numbers and even eleven digits (with the country code).
Example: Changes this 1234567890 into this (123) 456-7890
function formatphone($phone){
if (empty($phone)) return "";
if (strlen($phone) == 7) {
sscanf($phone, "%3s%4s", $prefix, $exchange);
} else if (strlen($phone) == 10) {
sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
} else if (strlen($phone) > 10) {
if(substr($phone,0,1)=='1') {
sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
} else {
sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
}
} else {
return $phone;
}
$out = "";
$out .= isset($country) ? $country.' ' : '';
$out .= isset($area) ? '(' . $area . ') ' : '';
$out .= $prefix . '-' . $exchange;
$out .= isset($extension) ? ' x' . $extension : '';
return $out;
}
I would like to thank Justin Cook for posting his code on justin-cook.com. By changing a few lines of Justin’s code, I was able to get it to work for me. To view the original code or to see Justin’s blog, visit: http://www.justin-cook.com/wp/2006/11/17/parse-and-format-phone-numbers-with-php/. Justin describes his blog as “A web, technology, programming and SEO blog by Justin Cook.” Nice work, Justin!
Buy Me a Coffee

