How to add characters in the middle of a line?
I am trying to format a number in the USA, such as 2121231234, in one with a dash: "212-123-1234."
I don’t know in advance how long the string of numbers will be,
it can be 12121231234, it can even be 0012121231234,
in this case I want it to turn into 1212-123-1234 and 001212-123-1234, respectively.
So far this is what I came 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 too much to accomplish such a simple task.
What am I missing?