且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中为美国电话号码添加破折号的功能

更新时间:2021-12-15 05:25:35

$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";