Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space after every 4th character

Tags:

php

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 ?

like image 864
user990767 Avatar asked Aug 04 '12 10:08

user990767


People also ask

How do you put a space between characters in a string?

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('').

How do you put a space after every character in a string python?

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.

How do I add a space between numbers in JavaScript?

To add space between numbers with JavaScript, we use the number toLocaleString method. const num = 1234567890; const result = num. toLocaleString("fr"); to call num.


2 Answers

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.

like image 191
Felix Kling Avatar answered Oct 08 '22 18:10

Felix Kling


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

like image 25
Olemak Avatar answered Oct 08 '22 19:10

Olemak