Format 10-digit string into hyphenated phone number
Asked Answered
C

6

1

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.

Camey answered 23/2, 2010 at 0:32 Comment(0)
C
7
$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.

Carrolcarroll answered 23/2, 2010 at 0:36 Comment(0)
F
3

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
}
Foti answered 23/2, 2010 at 0:43 Comment(0)
E
2
$p = $phone; 
echo "$p[0]$p[1]$p[2]-$p[3]$p[4]-$p[5]$p[6]$p[7]$p[8]";

Fewest function calls. :)

Erwin answered 23/2, 2010 at 3:31 Comment(0)
B
1
echo substr($phone, 0, 3) . '-' . substr($phone, 3, 3) . '-' . substr($phone, 6);

substr()

Busybody answered 23/2, 2010 at 0:37 Comment(0)
G
1

More regexp :)

$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);
Garlaand answered 23/2, 2010 at 11:22 Comment(0)
Y
0

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:

Yugoslav answered 16/7, 2022 at 1:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.