php - 使用 preg_match 在 PHP 中解析 A​​pache 日志

标签 php regex apache logging

我需要将数据保存在表中(用于报告、统计等...),以便用户可以按时间、用户代理等进行搜索。我有一个每天运行的脚本,用于读取 Apache 日志,然后将其插入在数据库中。

日志格式:

10.1.1.150 - - [29/September/2011:14:21:49 -0400] "GET /info/ HTTP/1.1" 200 9955 "http://www.domain.com/download/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"

我的正则表达式:

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

现在当我打印时:

print_r($matches);

Array
(
    [0] => 10.1.1.150 - - [29/September/2011:14:21:49 -0400] "GET /info/ HTTP/1.1" 200 9955 "http://www.domain.com/download/" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
    [1] => 10.1.1.150
    [2] => -
    [3] => -
    [4] => 29/September/2011
    [5] => 14:21:49
    [6] => -0400
    [7] => GET
    [8] => /info/
    [9] => HTTP/1.1
    [10] => 200
    [11] => 9955
    [12] => "http://www.domain.com/download/"
    [13] => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1"
)

我得到:"http://www.domain.com/download/" 和用户代理一样。我怎样才能摆脱正则表达式中的这些 "?奖金(有没有快速的方法可以轻松插入日期/时间)?

谢谢

最佳答案

要在 PHP 中解析 A​​pache access_log 日志,您可以使用这个正则表达式:

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

要匹配 Apache error_log 格式,您可以使用这个正则表达式:

$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

它匹配有或没有客户端的行:

[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

关于php - 使用 preg_match 在 PHP 中解析 A​​pache 日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603017/

相关文章:

javascript - 正则表达式在替换函数中使用变量无需重复

php - PHP 头函数的替代品

php - CodeIgniter 上 Assets 文件夹的路径

php - 使用bindValue进行PDO调试更新查询

javascript - 版本号验证

regex - grep 中匹配字符串的正则表达式

apache - 通过IP访问网站时如何将网站重定向到其域名-CentOS?

django - 使用 apache 和 mod_wsgi 时,我在哪里存储 django 项目代码?

php - SQL - 获取 ID 介于 5 和 10 之间的行..

php exec() rsync ssh 到远程服务器不起作用