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

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
echo wordwrap('12345678' , 4 , ' ' , true )

will output: 1234 5678

this should work as well.

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

Add a space between every 2 characters starting from the end of a string

use strrev() and chunk_split()

<?php

$str = 9010201;

echo trim(strrev(chunk_split(strrev($str),2, ' ')));

?>

adding a space after every character in a string in php?

tring in php named $password="1bsdf4";

output should be "1 b s d f 4"

$password="1bsdf4";    
echo $newtext = wordwrap($password, 1, "\n", true);

use implode you just need to use str_split first which converts the string to an array:

$password="1bsdf4";    
$formatted = implode(' ',str_split($password)); 

adding a space after every character in a string in php using regex

$formatted = preg_replace("/(.)/i", "\${1} ", $formatted);