PHP – adding characters in middle of a string (starting from the end)

characterphone-numberphpstringstring-formatting

How do you add characters in middle of a string?

I'm trying to format a US number such as 2121231234 into one with dashes like so: 212-123-1234.

I don't know in advance how long the string of numbers will be,
it might be 12121231234, it might even be 0012121231234,
in which case I want it to turn into 1212-123-1234, and 001212-123-1234, respectively.

So far, this is what I've come up with:

$phone_number = '2121231234';
$phone_number = str_split($phone_number); // [2,1,2,1,2,3,1,2,3,4]
$phone_number = array_reverse($phone_number); // [4,3,2,1,3,2,1,2,1,2]

array_splice($phone_number, 4, 0, '-'); // [4,3,2,1,-,3,2,1,2,1,2]
array_splice($phone_number, 8, 0, '-'); // [4,3,2,1,-,3,2,1,-,2,1,2]

$phone_number = array_reverse($phone_number); // [2,1,2,-,1,2,3,-,1,2,3,4]
$phone_number = implode($phone_number); // "212-123-1234"

Which works, but seems to be far too much to accomplish such a simple task.

What am I missing?

Best Solution

Try it with regular expressions:

echo preg_replace('/^(.*?)(.{3})(.{4})$/', '$1-$2-$3', $telnum);