medk medk - 1 year ago 101
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 Source

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) );

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download