medk medk - 8 days ago 6
PHP Question

Add spaces to string

How to add space after n characters in a string?

I have to format phone numbers to Swiss format:
0700000000 to become 070 000 00 00

So it has to be like a loop after 3 characters then 7 then 10

Answer

You don't need a loop. You can use a simple preg_split and then implode to put it back into a string, separated by a space.

echo implode(" ", preg_split("/(\d{3})(\d{3})(\d{2})(\d{2})/", "0700000000", -1, PREG_SPLIT_DELIM_CAPTURE) );

https://eval.in/684950

Comments