Search code examples
phpregexapachepreg-match

Preg_match apache log to PHP array


I want to get my apache's logs in PHP array to put them in the database, I tried this code :

$log = file_get_contents("path/to/my/apache/access_log");
$regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/';
preg_match($regex, $log, $matches);
print_r($matches);

It didn't work, the array is empty but i don't know why.

Thanks in advance for your help !


Solution

  • I was able to match the line with

    /^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+)/gm
    

    Note the m (multiline) ang g (global) flags at the end. You may also need to use preg_match_all function or yet better process the file one line at a time.