Add space after every 4th character

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

    Have you already seen this function called wordwrap? http://us2.php.net/manual/en/function.wordwrap.php

    Here is a solution. Works right out of the box like this.

    <?php
    $text = "Thiswordissoverylong.";
    $newtext = wordwrap($text, 4, "\n", true);
    echo "$newtext\n";
    ?>
    
    0 讨论(0)
  • 2021-02-11 12:33

    one-liner:

    $yourstring = "1234567890";
    echo implode(" ", str_split($yourstring, 4))." ";
    

    This should give you as output:
    1234 5678 90

    That's all :D

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

    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

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

    PHP3 Compatible:

    Try this:

    $strLen = strlen( $str );
    for($i = 0; $i < $strLen; $i += 4){
      echo substr($str, $i, 4) . ' ';
    } 
    unset( $strLen );
    
    0 讨论(0)
  • 2021-02-11 12:46

    The function wordwrap() basically does the same, however this should work as well.

    $newstr = '';
    $len = strlen($str); 
    for($i = 0; $i < $len; $i++) {
        $newstr.= $str[$i];
        if (($i+1) % 4 == 0) {
            $newstr.= ' ';
        }
    }
    
    0 讨论(0)
  • 2021-02-11 12:47

    Here is an example of string with length is not a multiple of 4 (or 5 in my case).

    function space($str, $step, $reverse = false) {
        
        if ($reverse)
            return strrev(chunk_split(strrev($str), $step, ' '));
        
        return chunk_split($str, $step, ' ');
    }
    

    Use :

    echo space("0000000152748541695882", 5);
    

    result: 00000 00152 74854 16958 82

    Reverse mode use ("BVR code" for swiss billing) :

    echo space("1400360152748541695882", 5, true);
    

    result: 14 00360 15274 85416 95882

    EDIT 2021-02-09

    Also useful for EAN13 barcode formatting :

    space("7640187670868", 6, true);
    

    result : 7 640187 670868

    short syntax version :

    function space($s=false,$t=0,$r=false){return(!$s)?false:(($r)?trim(strrev(chunk_split(strrev($s),$t,' '))):trim(chunk_split($s,$t,' ')));}
    

    Hope it could help some of you.

    0 讨论(0)
提交回复
热议问题