2013-02-12 66 views
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。 注意:每个记录可能有不同数量的行,并且可能不一定在其中包含单词错误。这更多的是“发现并匹配日期,然后在该记录中发现错误”类型的问题。

回答

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

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

+0

我有点知道该怎么做(查看问题中的标签)!它发现错误和日期,让我头痛! :( – 2013-02-12 16:06:36

+0

更好吗?我已经完成了关键字搜索的单词'错误'和'['字符来定位错误和日期。 – Husman 2013-02-12 16:11:30

+0

编辑时发现第一个日期(这是最后一个日期因为我们正在向后读) – Husman 2013-02-12 16:40:32