Strawberry
Strawberry

Reputation: 67888

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.

Upvotes: 1

Views: 5332

Answers (6)

mickmackusa
mickmackusa

Reputation: 47934

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:

Upvotes: 1

Adi
Adi

Reputation: 556

More regexp :)

$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);

Upvotes: 1

codeholic
codeholic

Reputation: 5848

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
}

Upvotes: 3

Steve Clay
Steve Clay

Reputation: 8781

$p = $phone; 
echo "$p[0]$p[1]$p[2]-$p[3]$p[4]-$p[5]$p[6]$p[7]$p[8]";

Fewest function calls. :)

Upvotes: 2

Erik
Erik

Reputation: 20722

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

Upvotes: 7

Amber
Amber

Reputation: 526793

echo substr($phone, 0, 3) . '-' . substr($phone, 3, 3) . '-' . substr($phone, 6);

substr()

Upvotes: 1

Related Questions