Skip to content
Advertisement

Function to add dashes to US phone number in PHP

What is the best way to add dashes to a phone number in PHP? I have a number in the format xxxxxxxxxx and I want it to be in the format xxx-xxx-xxxx. This only applies to 10 digit US phone numbers.

Advertisement

Answer

$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";
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement