0

我有一个文本文件,例如:

================================================
[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

现在我想向后读取这个文件,对于我在新日期的记录中找到的每个错误,我需要做一些事情。我需要帮助 1) 向后读取文件,直到遇到日期并保存该日期,2) 在此之前将所有行作为字符串抓取并在其中找到单词 Error。注意:每条记录可能有不同的行数,并且不一定包含错误一词。这更像是“查找并匹配日期,然后在该记录中查找错误”类型的问题。

4

1 回答 1

1
$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;
        }
    }
}

读取一个文件,并将其转换为一个数组,然后将数组反转为反向遍历,然后打印出最后一个日期。

于 2013-02-12T16:05:15.723 回答