1

I am attempting to split a log file by up to every nth line instead of every line. Currently I am using preg_split for line breaks which gives me a new array element for each line. I am trying to split by nth line.

$str = file_get_contents('filename');
$arr1 = preg_split("/\r\n|\n|\r/", $str, -1, PREG_SPLIT_NO_EMPTY);    

2 Answers2

3

You could alternatively try something like this?

$chunks = array_chunk( file( $filename ), 5 );
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • This should work perfectly for me. If you could expand on your explanation. Array_chunk() splits an array into n arrays, based on the second parameter. Why in this example is it splitting based on file line breaks? –  Jun 24 '17 at 19:45
  • Sorry - had to stop for dinner. Yep - using `file` takes the contents of the file in question and turns it into an array. `array_chunk` is a built-in PHP function to split an array into a series of arrays of `n` length. There are a number of options you could set ( flags ) to `file` but I think by default it splits the file contents on a line-break which is ideal as that was more or less what you were trying to do with a regex – Professor Abronsius Jun 24 '17 at 20:41
1

How about

/(.*(\r\n|\n|\r)){5}/g

where you can change the {5} to 2 if you want split by 2 lines instead of 5?

Bizmate
  • 1,835
  • 1
  • 15
  • 19