Split string into equal parts using PHP

后端 未结 5 1021
既然无缘
既然无缘 2020-12-06 10:35

I\'d like to get a string, for example \'sdasdasdsdkjsdkdjbskdbvksdbfksjdbfkdbfksdjbf\' and split that up every six charaters.

I don\'t think explode or strtok will

相关标签:
5条回答
  • 2020-12-06 10:48

    str_split was designed for just that.

    $str = "sdasdasdsdkjsdkdjbskdbvksdbfksjdbfkdbfksdjbf";
    $parts = str_split($str, 6);
    print_r($parts);
    
    0 讨论(0)
  • 2020-12-06 10:59

    You want chunk_split()

    0 讨论(0)
  • 2020-12-06 11:04

    Not the cleanest way but it works.

    <?php
    $MyString = 'asdfasdlkfjasdlkfjasdlkfjasldkfj';
    $MyNewString;
    $n = 6; // How many you want before seperation
    $MyNewString = substr($MyString,0,$n); 
    $i = $n;
    while ($i < strlen($MyString)) {
            $MyNewString .= '-'; // Seperator Character
            $MyNewString .= substr($MyString,$i,$n);
            $i = $i + $n;
    }
    echo $MyNewString
    ?>
    
    0 讨论(0)
  • 2020-12-06 11:05
    $str = 'abcdefghijklmnopqrstuvwxyz';
    $i = 0; $len = 6; $bits = array();
    while($i < strlen($str)) {
        $bits[] = substr($str, $i, $len);
        $i += $len;
    }
    

    Edit: or use str_split as suggested (php has too many functions built in ffs!)

    0 讨论(0)
  • 2020-12-06 11:12

    See the docs on str_split.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题