This is a function that uses the inbuilt PHP sscanf funtion to format phone numbers that users input into a form into a perfect number. The functino strips all non-numeric characters (dashes, dots, parantheses), extracts extensions, and even picks up the area and country code.
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 "unknown phone format: $phone";
$out = "";
$out .= isset($country) ? $country.' ' : '';
$out .= isset($area) ? '(' . $area . ') ' : '';
$out .= $prefix . '-' . $exchange;
$out .= isset($extension) ? ' x' . $extension : '';
return $out;
}
2 Comments
i was looking for something exactly like this however something appears to not be working correctly with the code. I've tried working with it and can't for the life of me figure out where to begin.
any chance you might be able to revise this?
I started working out my own idea and got half way and decided there are too many possible entries that could be submitted. You idea seems to cover common formats and then fall back to unknown and let it slide by.
looks like we are both heading down the same idea though
thanks for the inspiration 🙂
this code is broken in more ways than one. not sure why it was posted. take the two consecutive else statements, for example. wtF?