Parse Apache log in PHP using preg_match Parse Apache log in PHP using preg_match apache apache

Parse Apache log in PHP using preg_match


To parse an Apache access_log log in PHP you can use this regex:

$regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/';preg_match($regex ,$log, $matches);

To match the Apache error_log format, you can use this regex:

$regex = '/^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i';preg_match($regex, $log, $matches);$matches[1] = Date and time,           $matches[2] = severity,$matches[3] = client addr (if present) $matches[4] = log message

It matches lines with or without the client:

[Tue Feb 28 11:42:31 2012] [notice] Apache/2.4.1 (Unix) mod_ssl/2.4.1 OpenSSL/0.9.8k PHP/5.3.10 configured -- resuming normal operations[Tue Feb 28 14:34:41 2012] [error] [client 192.168.50.10] Symbolic link not allowed or link target not accessible: /usr/local/apache2/htdocs/x.js


If you don't want to capture the double quotes, move them out of the capture groups.

 (\".*?\") 

Should become:

 \"(.*?)\"

As alternative you could just post-process the entries with trim($str, '"')


your regexp are wrong.you shoudl use correct regexp

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