在PHP中为美国电话号码添加破折号的功能 [英] Function to add dashes to US phone number in PHP
本文介绍了在PHP中为美国电话号码添加破折号的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP中将破折号添加到电话号码的最佳方法是什么?我有一个格式为xxxxxxxxxx
的数字,我希望它的格式为xxx-xxx-xxxx.这仅适用于10位数的美国电话号码.
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.
推荐答案
$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";
这篇关于在PHP中为美国电话号码添加破折号的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文