zeusukdm
zeusukdm

Reputation: 155

Adding line break after every 6th comma

I have string like 21,22,23,24,25,26,27,28,31,32,33,34,35,36,37,38 how can I add a line break after every 6th comma?

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

Upvotes: 1

Views: 361

Answers (4)

zrinath
zrinath

Reputation: 106

Simply do it with this function,

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);

Upvotes: 0

ewcz
ewcz

Reputation: 13087

one approach could be to split the input strings, group individual parts into chunks of fixed size and then join these chunks back:

$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);

this produces

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

The code above can be further shortened as:

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

Upvotes: 5

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using array_chunk, array_map, explode and implode functions:

$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);

The output:

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

Upvotes: 1

Evinn
Evinn

Reputation: 153

this is the logic that i can think about it, ignore it if its gonna affect performace,

$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;

Upvotes: 0

Related Questions