Search code examples
phpdatetimetext-extraction

Get datetime value from a qualifying line in a .txt file then reformat the datetime value


I have this a file named "test.txt" which has the following content:

BEGIN_GENERAL 8
LastLine 20130801000028 136606 57288915 25883895742573
FirstTime 20130701130426
LastTime 20130731235941
LastUpdate 20130802015823 1 0 0 0 0
TotalVisits 360
TotalUnique 246
MonthHostsKnown 0
MonthHostsUnknown 454
END_GENERAL

and I would like a function that extract "LastUpdate" and "20130802015823 1 0 0 0 0" by changing it to a date in PHP.

So I've tried this :

preg_match("/BEGIN_GENERAL(.*)END_GENERAL/is", $test, $matches);
$text= $matches;

Solution

  • You can use Regular Expressions in PHP to do this.

    <?php
    
    $data = file_get_contents('test.txt');
    
    preg_match('/^LastUpdate ([0-9]{14}) /ms', $data, $matches);
    
    $last_update_date = date("Y-m-d H:i:s", strtotime($matches[1]));
    
    print $last_update_date;