Add space after every 4th character

Viewed 77653

I want to add a space to some output after every 4th character until the end of the string. I tried:

$str = $rows['value'];
<? echo substr($str, 0, 4) . ' ' . substr($str, 4); ?>

Which just got me the space after the first 4 characters.

How can I make it show after every 4th ?

9 Answers

Here is an example of string with length is not a multiple of 4 (or 5 in my case).

function space($str, $step, $reverse = false) {
    
    if ($reverse)
        return strrev(chunk_split(strrev($str), $step, ' '));
    
    return chunk_split($str, $step, ' ');
}

Use :

echo space("0000000152748541695882", 5);

result: 00000 00152 74854 16958 82

Reverse mode use ("BVR code" for swiss billing) :

echo space("1400360152748541695882", 5, true);

result: 14 00360 15274 85416 95882

EDIT 2021-02-09

Also useful for EAN13 barcode formatting :

space("7640187670868", 6, true);

result : 7 640187 670868

short syntax version :

function space($s=false,$t=0,$r=false){return(!$s)?false:(($r)?trim(strrev(chunk_split(strrev($s),$t,' '))):trim(chunk_split($s,$t,' ')));}

Hope it could help some of you.

Related