PHP - adding characters in the middle of a line (starting from the end)

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?

+5
source share
3 answers

:

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

$phone_number = "2121231234";
$phone_number = substr($phone_number, 0, 3) . '-' . substr($phone_number, 3, 6) . ' - '.
substr($phone_number, 6, strlen($phone_number));
+2

$phone_number = substr_replace($phone_number, '-' , strlen($phone_number)-7 , 0);
$phone_number = substr_replace($phone_number, '-' , strlen($phone_number)-4 , 0);
0

All Articles