Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 696
John Alt Avatar asked May 18 '11 05:05

John Alt


2 Answers

Try it with regular expressions:

echo preg_replace('/^(.*?)(.{3})(.{4})$/', '$1-$2-$3', $telnum);
like image 159
deceze Avatar answered Sep 21 '22 15:09

deceze


Try it

$phone_number = "2121231234";
$phone_number = substr($phone_number, 0, 3) . '-' . substr($phone_number, 3, 6) . ' - '.
substr($phone_number, 6, strlen($phone_number));
like image 39
totali Avatar answered Sep 22 '22 15:09

totali