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 ?
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').
We add space in string in python by using rjust(), ljust(), center() method. To add space between variables in python we can use print() and list the variables separate them by using a comma or by using the format() function.
To add space between numbers with JavaScript, we use the number toLocaleString method. const num = 1234567890; const result = num. toLocaleString("fr"); to call num.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With