【问题标题】:Reverse reading a text file till a random date is encountered反向读取文本文件直到遇到随机日期
【发布时间】:2013-02-12 16:00:41
【问题描述】:

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

================================================
[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。 注意:每条记录可能有不同的行数,并且不一定包含错误一词。这更像是“查找并匹配日期,然后在该记录中查找错误”类型的问题。

【问题讨论】:

    标签: php file array-reverse


    【解决方案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;
            }
        }
    }
    

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

    【讨论】:

    • 我有点知道该怎么做(请参阅问题中的标签)!它找到了让我头疼的错误和日期! :(
    • 更好吗?我已经对单词“error”和“[”字符进行了关键字搜索,以定位错误和日期。
    • 编辑为在找到第一个日期(这是我们向后阅读后的最后一个日期)时跳出循环
    • 第一次打破它的问题是在日期之前有一行也有[]。我没有想到这个逻辑,这就是为什么我没有包括它。那么,如何获取包含日期的整行呢?
    • 另外,现在想想,我认为我不需要代码中的break。对于保存日期的行,我每次都会抓住第二行。但是,我如何抓住整条线? echo $f[1] 不显示第二行!! ://
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多