Jump to content

Split $string to several smaller chunks of lines


transparencia

Recommended Posts

My string is like this:

 

line 1

line 2

....

line 3453

line 3454

etc...

 

I want to split the string into chunks of 500 lines, do something with those chunks and then reassamble the main $string again. The last chunk doesn't need to be 500 lines it can be less.

 

How can I do it?

something like this will get you started.

 

//text array
$my500lines = array();
$tempText = '';

$string = "line 1
line 2
....
line 3453
line 3454
etc...";

$count = 0;

foreach(preg_split("/(\r?\n)/", $string) as $line){
    $count++;

if ($count == 500)
{
//reset count and temptext
$my500lines[] = $tempText;
$tempText = '';
$count = 0;
}
else
{
$tempText .= $line;
}

}

Might be a little shorter:

 

 

$lines = explode(PHP_EOL, $string);$newchunks = array();while($chunk = array_splice($lines, 0, 500)) {// do something with lines in $chunk$newchunks = array_merge($newchunks, $chunk);}$newstring = implode(PHP_EOL, $newchunks);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.