Function to add dashes to US phone number in PHP

$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
  $number = substr($number, 0, 3) .'-'.
            substr($number, 3, 3) .'-'.
            substr($number, 6);
}

Or if you for some reason want to avoid substr:

$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
  $parts = str_split($number, 3);
  $number = $parts[0] .'-'. $parts[1] .'-'. $parts[3].$parts[4];
}

$number = "1234567890";
$formatted_number = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);

EDIT: To be a bit more generic and normalize a US phone number given in any of a variety of formats (which should be common practice - there's no reason to force people to type in a phone number in a specific format, since all you're interested in are the digits and you can simply discard the rest):

function localize_us_number($phone) {
  $numbers_only = preg_replace("/[^\d]/", "", $phone);
  return preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $numbers_only);
}

echo localize_us_number("5551234567"), "\n";
echo localize_us_number("15551234567"), "\n";
echo localize_us_number("+15551234567"), "\n";
echo localize_us_number("(555) 123-4567"), "\n";
echo localize_us_number("+1 (555) 123-4567"), "\n";
echo localize_us_number("Phone: 555 1234567 or something"), "\n";

I feel obliged to post. Cheesiest solution:

$number = "1234567890";
$formatted_number = "$number[0]$number[1]$number[2]-$number[3]$number[4]$number[5]-$number[6]$number[7]$number[8]$number[9]";

But it works and its fast. vs. the preg_replace solution:

250,000 iterations:

preg_replace: 1.23 seconds ugly solution: 0.866 seconds

Pretty meaningless but fun :P


iterate through the string and make counter. When counter is 3 or 7 insert dash.

Tags:

Php