Comparing dates and times inside a text file

Discussion in 'PHP' started by newphpuser, Jan 7, 2013.

  1. #1
    Hello Everyone,

    I have different entries in a log file in the form:

    I want to grab the time in the first line of the record (I can manage that with a RegEx, alright!) and then compare it with the time of the next entry (in this case, with Jan 27 12:12:57). And if the second time is greater than the first, I want to read the rest of the text file and do a bunch of other things.Is it possible to do this?
    NOTE: The entries may have records of any number of lines, but each entry is separated by the === delimiter.
     
    Solved! View solution.
    newphpuser, Jan 7, 2013 IP
  2. #2
    The "easy" bit is splitting up the entries:

    <?php
    
    $filecontents = file_get_contents("events.log");
    
    $logentries = explode("================================================", $filecontents);
    
    array_shift($logentries);
    
    ?>
    PHP:
    The problem with that is you have two entries in the array to reflect one event.

    <?php $lines = count($logentries)/3; ?>
    PHP:
    This should solve that, though.

    Match up the date entries:

    <?php $pattern = "/([a-zA-Z]{3}) ([0-9]{2}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/i"; ?>
    PHP:
    These variables are used to know which entries to check:

    <?php
    $time = 0;
    $nexttime = 0;
    ?>
    PHP:
    Then run the check itself:

    <?php
    for($i = 0; $i < $lines; $i++) {
        preg_match($pattern, $logentries[$time], $match1);
        $nexttime = $nexttime+2;
        preg_match($pattern, $logentries[$nexttime], $match2);
        if(strtotime($match1[0]) < strtotime($match2[0])) {
            print("true");
        } else {
            print("false");
        }
        $time = $time+2;
    }
    ?>
    PHP:
    Assuming I've understood what you want to do.

    I'm sure someone more skilled at PHP can show you a better way to do it.
     
    ryan_uk, Jan 8, 2013 IP
  3. newphpuser

    newphpuser Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, ryan_uk! :)
     
    newphpuser, Jan 8, 2013 IP