每隔6个逗号后添加换行符

时间:2017-03-21 07:47:56

标签: php

我有像 21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38 这样的字符串我怎样才能添加一个每6个逗号后换行?

    21,22,23,24,25,26,
    27,28,31,32,33,34,
    35,36,37,38

4 个答案:

答案 0 :(得分:4)

一种方法可能是分割输入字符串,将各个部分分组为固定大小的块,然后将这些块连接起来:

$s="21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38";

$arr = explode(",", $s);
$chunks = array_chunk($arr, 6);

$L = array();
foreach($chunks as $chunk){
    $L[] = implode(",", $chunk);
}
$ret = implode(",\n", $L);
var_dump($ret);

这会产生

string(49) "21,22,23,24,25,26,
27,28,31,32,33,34,
35,36,37,38"

上述代码可以进一步缩短为:

$arr = explode(",", $s);
$chunks = array_chunk($arr, 6);
$ret = implode(",\n", array_map(function($x){ return implode(",", $x);}, $chunks));

答案 1 :(得分:1)

使用array_chunkarray_mapexplodeimplode函数的解决方案:

$s = "21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38";
$chunks = array_chunk(explode(",", $s), 6);

$result = rtrim(implode(PHP_EOL, array_map(function($v) { 
    return implode(',', $v) . ','; 
}, $chunks)), ',');

print_r($result);

输出:

21,22,23,24,25,26,
27,28,31,32,33,34,
35,36,37,38

答案 2 :(得分:0)

这是我能想到的逻辑, 忽视它,如果它会影响性能,

$s = "21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38";
    $loop = explode(",",$s);
    $new_val = '';
    $counter = 1;
    foreach($loop as $key=>$val)
    {
        $new_val .= $val.',';
        if($counter % 6 ==0)
        {
            $new_val .= '\n';
        }
        $counter++;
    }
    echo $new_val;

答案 3 :(得分:0)

只需使用此功能

即可
function insertNewline($str, $delim, $pos){
    return preg_replace('/((.*?'.$delim.'){'.$pos.'})/',"$1" . PHP_EOL,$str);
}

$x = "21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38";
echo insertNewline($x, ',', 6);