开发者

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 1234开发者_JAVA百科56790 to 123-456-7890 as phone numbers are typically formatted in the USA.


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

substr()


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.

As a non-regex alternative, you could parse the string and reformat it using placeholders with sscanf() and vprintf().

Codes: (Demo)

$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:

  • https://github.com/giggsey/libphonenumber-for-php/blob/master/docs/PhoneNumberUtil.md
  • https://github.com/brick/phonenumber
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜