2013-02-12 164 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

相關問題