Nancy
Nancy

Reputation: 504

Explode to break line after every other comma

I am trying to insert break line after every other comma when I echo my $model varible which consists of list of many different models for each product which is pulled out from mysql database. I am trying to do it with explode, but am failing, because it only shows the first row of 2 (model1, model2). Other models from the list are missing. What I have so far is:

   <?php 
$commasCount = count(explode(',', $model));
if ($commasCount > 2) {
    $model = preg_replace('~,[^,]*,~', "\$0\n", $model);

}
echo $model;
 ?>

My question is - How do I show the full list of models two by two in a row and not just the first two records? Thank you.

Upvotes: 2

Views: 232

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627086

Regarding

I am trying to insert break line after every other comma

You may use a preg_replace with the following regex:

$model = preg_replace('~,[^,]*,~', "\$0\n", $model);

or - if you render the output in a Web browser:

$model = preg_replace('~,[^,]*,~', "\$0<br/>", $model);

Here is the regex demo.

Basically, matching comma, 0+ symbols other than comma (with [^,]*), and again a comma, and then replacing the matched text with itself ($0) adding a line break.

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

You can use array_chunk to group items two by two:

$models = array_chunk(explode(',', $model), 2);
$pairs = array_map(function ($i) {
    return implode(',', $i);
}, $models);
$result = implode(",\n", $pairs);

Upvotes: 0

Related Questions