[英]Format 10-digit string into hyphenated phone number
I have a string containing a ten-digit phone number and I want to format it with hyphens.我有一个包含十位数电话号码的字符串,我想用连字符对其进行格式化。
I am seeking a way to convert 123456790
to 123-456-7890
as phone numbers are typically formatted in the USA.我正在寻找一种将
123456790
转换为123-456-7890
的方法,因为电话号码通常在美国格式化。
$areacode = substr($phone, 0, 3);
$prefix = substr($phone, 3, 3);
$number = substr($phone, 6, 4);
echo "$areacode-$prefix-$number";
You could also do it with regular expressions:你也可以用正则表达式来做到这一点:
preg_match("/(\d{3})(\d{3})(\d{4})/",$phone,$matches);
echo "$matches[1]-$matches[2]-$matches[3]";
There are more ways, but either will work.还有更多方法,但任何一种都可以。
The following code will also validate your input.以下代码还将验证您的输入。
preg_match('/^(\d{3})(\d{3})(\d{4})$/', $phone, $matches);
if ($matches) {
echo(implode('-', array_slice($matches, 1)));
}
else {
echo($phone); // you might want to handle wrong format another way
}
$p = $phone;
echo "$p[0]$p[1]$p[2]-$p[3]$p[4]-$p[5]$p[6]$p[7]$p[8]";
Fewest function calls.最少的函数调用。 :)
:)
echo substr($phone, 0, 3) . '-' . substr($phone, 3, 3) . '-' . substr($phone, 6);
More regexp :)更多正则表达式:)
$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);
If using a regular expression, I would not bother creating a temporary array to conver back into a string.如果使用正则表达式,我不会费心创建一个临时数组来转换回字符串。 Instead just tell
preg_replace()
to make a maximum of two replacements after each sequence of three digits.相反,只需告诉
preg_replace()
在每个三位数序列之后最多进行两次替换。
As a non-regex alternative, you could parse the string and reformat it using placeholders with sscanf()
and vprintf()
.作为非正则表达式的替代方案,您可以解析字符串并使用带有
sscanf()
和vprintf()
的占位符重新格式化它。
$string = '1234567890';
echo preg_replace('/\d{3}\K/', '-', $string, 2);
// 123-456-7890
Or或者
vprintf('%s-%s-%s', sscanf($string, '%3s%3s%4s'));
// 123-456-7890
Or或者
echo implode('-', sscanf($string, '%3s%3s%4s'));
// 123-456-7890
For such a simple task, involving a library is super-overkill, but for more complicated tasks there are libraries available:对于这样一个简单的任务,涉及一个库是超级大材小用,但对于更复杂的任务,有可用的库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.