Add space after every 4th character

前端 未结 8 1883
我寻月下人不归
我寻月下人不归 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: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);
    

提交回复
热议问题