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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Strawberry
  • 66,024
  • 56
  • 149
  • 197

6 Answers6

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.

Erik
  • 20,526
  • 8
  • 45
  • 76
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
}
codeholic
  • 5,680
  • 3
  • 23
  • 43
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. :)

Steve Clay
  • 8,671
  • 2
  • 42
  • 48
1
echo substr($phone, 0, 3) . '-' . substr($phone, 3, 3) . '-' . substr($phone, 6);

substr()

Amber
  • 507,862
  • 82
  • 626
  • 550
1

More regexp :)

$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);
Adi
  • 556
  • 1
  • 3
  • 8
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:

mickmackusa
  • 43,625
  • 12
  • 83
  • 136