Add space after every 4th character

前端 未结 8 1874
我寻月下人不归
我寻月下人不归 2021-02-11 12:19

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

$str = $rows[\'value\'];


        
相关标签:
8条回答
  • 2021-02-11 12:48

    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.

    0 讨论(0)
  • 2021-02-11 12:50

    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);
    
    0 讨论(0)
提交回复
热议问题