Add space after every 4th character

Php

Php Problem Overview


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 ?

Php Solutions


Solution 1 - Php

You can use chunk_split [docs]:

$str = chunk_split($rows['value'], 4, ' ');

DEMO

If the length of the string is a multiple of four but you don't want a trailing space, you can pass the result to trim.

Solution 2 - Php

Wordwrap does exactly what you want:

echo wordwrap('12345678' , 4 , ' ' , true )

will output: 1234 5678

If you want, say, a hyphen after every second digit instead, swap the "4" for a "2", and the space for a hyphen:

echo wordwrap('1234567890' , 2 , '-' , true )

will output: 12-34-56-78-90

Reference - wordwrap

Solution 3 - Php

Have you already seen this function called wordwrap? http://us2.php.net/manual/en/function.wordwrap.php

Here is a solution. Works right out of the box like this.

<?php
$text = "Thiswordissoverylong.";
$newtext = wordwrap($text, 4, "\n", true);
echo "$newtext\n";
?>

Solution 4 - Php

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.

Solution 5 - Php

On way would be to split into 4-character chunks and then join them together again with a space between each part.

As this would technically miss to insert one at the very end if the last chunk would have exactly 4 characters, we would need to add that one manually (Demo):

$chunk_length = 4;
$chunks = str_split($str, $chunk_length);
$last = end($chunks);
if (strlen($last) === $chunk_length) {
    $chunks[] = '';
}
$str_with_spaces = implode(' ', $chunks);

Solution 6 - Php

one-liner:

$yourstring = "1234567890";
echo implode(" ", str_split($yourstring, 4))." ";

This should give you as output:
1234 5678 90

That's all :D

Solution 7 - Php

The function wordwrap() basically does the same, however this should work as well.

$newstr = '';
$len = strlen($str); 
for($i = 0; $i < $len; $i++) {
    $newstr.= $str[$i];
    if (($i+1) % 4 == 0) {
        $newstr.= ' ';
    }
}

Solution 8 - Php

PHP3 Compatible:

Try this:

$strLen = strlen( $str );
for($i = 0; $i < $strLen; $i += 4){
  echo substr($str, $i, 4) . ' ';
} 
unset( $strLen );

Solution 9 - Php

StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - 4;
while (idx > 0){
  str.insert(idx, " ");
  idx = idx - 4;
}
return str.toString();

Explanation, this code will add space from right to left:

 str = "ABCDEFGH" int idx = total length - 4; //8-4=4
    while (4>0){
        str.insert(idx, " "); //this will insert space at 4th position
        idx = idx - 4; // then decrement 4-4=0 and run loop again
    }

The final output will be:

ABCD EFGH

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser990767View Question on Stackoverflow
Solution 1 - PhpFelix KlingView Answer on Stackoverflow
Solution 2 - PhpOlemakView Answer on Stackoverflow
Solution 3 - PhpSgarzView Answer on Stackoverflow
Solution 4 - PhpMelomanView Answer on Stackoverflow
Solution 5 - PhphakreView Answer on Stackoverflow
Solution 6 - PhpGiovaView Answer on Stackoverflow
Solution 7 - PhpfdomigView Answer on Stackoverflow
Solution 8 - PhpEvaView Answer on Stackoverflow
Solution 9 - PhpNitin DivateView Answer on Stackoverflow