Max Thorley
Max Thorley

Reputation: 173

PHP newline after 10th comma

I need to split the following string:

333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823

into separate lines where a new line begins after the last 10th comma, if that makes any sense?

So it looks like this:

333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,

528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,

710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823

Upvotes: 2

Views: 906

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Please check the comments for explanation:-

 <?php
    error_reporting(E_ALL); // check if any error occur
    ini_set('display_errors',1); // display error
    $string = '333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823'; // original string
    echo $string; // echo original string
    $array = explode(',',$string); // explode string with comma to make it array
    echo "<pre/>";print_r($array); // print array
    $chunked_array = array_chunk($array,10); // chunk array to each 10 counts and make a multidimensional array
    $new_string = ''; // create a new empty string
    foreach ($chunked_array as $chunked_ar){ // iterate through multi-dimensional array 

      $new_string .= implode(',',$chunked_ar)."\n"; // convert each array to string and add new line and assign it to new string variable
    }
    echo $new_string; // echo new variable.
  ?>

Output:- https://eval.in/557389

Note : Adding error_reporting code (first two lines after <?php) is always a very good practice to find out errors and resolve them. Thanks.

Upvotes: 1

Damian Polac
Damian Polac

Reputation: 934

You can do that with one-liner.

preg_replace('/((.*?,){10})/', "$1\n", $text);

Upvotes: 1

Barry
Barry

Reputation: 3318

This will do that...

$str = '333 ,351 ,359 ,360 ,370 ,371 ,385 ,492 ,512 ,514 ,528 ,539 ,546 ,628 ,630 ,634 ,636 ,702 ,706 ,709 ,710 ,715 ,718 ,719 ,763 ,770 ,803 ,822 ,823';

$iCount = 0;
foreach (explode(',',$str) as $iNum)
    echo $iNum.' ,'.(++$iCount % 10 == 0 ? '<br>' : '');

Upvotes: 1

Webeng
Webeng

Reputation: 7113

Assuming $string is that previous string of yours:

<?php

$myArray = explode(",", $string);
$newString = "";
$count = 0;
foreach ($myArray as $value)
{
  $newString = $newString.$value.",";
  $count++;
  if ($count==10)
  {
    $count=0;
    $newString = $newString."\n";
  }
}

?>

Upvotes: 1

Related Questions