Search code examples
phpfilearray-reverse

Reverse reading a text file till a random date is encountered


I have a text file like:

================================================
[Feb 11 2013 13:17:14] - some string here and here
General options - [something]
Line y
================================================
Line 1
Line 2
Line 3
Line 4
Line 5     
Something here. Error message: ReferenceError: applyMetadataTemplate is undefined; line: 625  
Line 7
================================================
[Feb 11 2013 16:07:14] - some string here and here
General options - [something]
Line y
================================================
Line 1
Line 2
Line 3
Line 4
Line 5     
Something here. Error message: ReferenceError: applyMetadataTemplate is undefined; line: 625  
Line 7

Now I want to read this file backwards and for each Error that I find inside a record with a new date, I need to do something. I need help 1) reading the file backwards until I encounter the date and saving that date, 2) Grabbing all the lines until then as a string and finding the word Error inside it. Note: Each record may have different number of lines and may not necessarily have the word error inside it. It's more a "finding and matching the date and then finding error inside that record" type of problem.


Solution

  • $matches = array();    
    $file = file("log.txt");
    $file = array_reverse($file);
    foreach($file as $f){
        if (stripos($f, "[") !== false) { 
            // Check string for date by regex 
            preg_match('/(\D*) (\d{2}) (\d{4})/', $f, $matches);
    
            // Check that parts of the date were found
            if(count($matches) > 2) {
                echo $f; //print the line
                break;
            }
        }
    }
    

    Read a file, and convert it into an array, then reverse the array for backward traversal, then print out the last date.