Click to See Complete Forum and Search --> : How to put spaces in a string?


callumd
10-22-2007, 12:36 AM
Let's say I have a string, that contains random numbers and letters:


$string = '12hd67dgbf40dkfgeqw647nkd873d73';

I would like to put spaces in this string after every 4th character, so that the sting would look like:

12hd 67dg bf40 dkfg eqw6 47nk d873 d73

The technique would need to work on strings of any length.

I have some ideas, but they're all pretty rough. I am guessing there must be some PHP function I could use to help me.

Any suggestions?

callumd
10-22-2007, 01:25 AM
Got it:

$cc = '12345678901234567890';

$i=4;

while ((substr($cc, $i)) != NULL) {

$cc = substr($cc, 0, $i) . ' ' . substr($cc, $i);

$i = ($i + 5);
}

NogDog
10-22-2007, 01:58 AM
An alternative:

$cc = trim(chunk_split($cc, 4, ' '));