transparencia Posted September 27, 2010 Share Posted September 27, 2010 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? Link to comment https://forums.phpfreaks.com/topic/214517-split-string-to-several-smaller-chunks-of-lines/ Share on other sites More sharing options...
joel24 Posted September 27, 2010 Share Posted September 27, 2010 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; } } Link to comment https://forums.phpfreaks.com/topic/214517-split-string-to-several-smaller-chunks-of-lines/#findComment-1116275 Share on other sites More sharing options...
AbraCadaver Posted September 27, 2010 Share Posted September 27, 2010 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); Link to comment https://forums.phpfreaks.com/topic/214517-split-string-to-several-smaller-chunks-of-lines/#findComment-1116314 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.