Splitting a large Apache log file with PHP

[code language=’php’]
$months = array(
  ‘Jul’ => ’07’,
  ‘Aug’ => ’08’,
  ‘Sep’ => ’09’
);

$open_file = false;
$fw = false;

$fp = fopen(‘filename.log’, ‘r’);

while($line = fgets($fp)) {
  preg_match(‘:([0-9]{2})/(Jul|Aug|Sep):’, $line, $matches);
  // $matches[1] = day of month
  // $matches[2] = month name
  $filename = “filename.log.2007{$months[$matches[2]]}{$matches[1]}”;
  if($filename != $open_file) {
    if($fw) {
      fclose($fw);
    }
    $fw = fopen($filename, ‘a’);
    $open_file = $filename;
    echo “$filename\n”;
  }
  fputs($fw, $line);
}

fclose($fw);
fclose($fp);
[/code]