PHP/regex解析NGINX错误日志

标签 php regex

错误条目如下所示:

2011/06/10 13:30:10 [error] 23263#0: *1 directory index of "/var/www/ssl/" is forbidden, client: 86.186.86.232, server: hotelpublisher.com, request: "GET / HTTP/1.1", host: "hotelpublisher.com"

我需要解析:

date/time
error type
error message
client
server
request
host

第一位(解析日期)使用 substr 很容易。虽然我的 REGEX 不太好,但我希望听到更好的解决方案。我猜想,简单地按 , 分解也不会奏效,因为错误也可能包含逗号。

最有效的方法是什么?

最佳答案

关于:

$str = '2011/06/10 13:30:10 [error] 23263#0: *1 directory index of "/var/www/ssl/" is forbidden, client: 86.186.86.232, server: hotelpublisher.com, request: "GET / HTTP/1.1", host: "hotelpublisher.com"';
preg_match('~^(?P<datetime>[\d+/ :]+) \[(?P<errortype>.+)\] .*?: (?P<errormessage>.+), client: (?P<client>.+), server: (?P<server>.+), request: (?P<request>.+), host: (?P<host>.+)$~', $str, $matches);
print_r($matches);

输出:

Array
(
    [0] => 2011/06/10 13:30:10 [error] 23263#0: *1 directory index of "/var/www/ssl/" is forbidden, client: 86.186.86.232, server: hotelpublisher.com, request: "GET / HTTP/1.1", host: "hotelpublisher.com"
    [datetime] => 2011/06/10 13:30:10
    [1] => 2011/06/10 13:30:10
    [errortype] => error
    [2] => error
    [errormessage] => *1 directory index of "/var/www/ssl/" is forbidden
    [3] => *1 directory index of "/var/www/ssl/" is forbidden
    [client] => 86.186.86.232
    [4] => 86.186.86.232
    [server] => hotelpublisher.com
    [5] => hotelpublisher.com
    [request] => "GET / HTTP/1.1"
    [6] => "GET / HTTP/1.1"
    [host] => "hotelpublisher.com"
    [7] => "hotelpublisher.com"
)

关于PHP/regex解析NGINX错误日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307203/

相关文章:

php - MVC,CodeIgniter,在 View 中使用条件语句?

php - Mysql:如何修剪和比较数据库字段与字母数字值?

regex - R - 提取所有匹配模式的字符串并创建关系表

python 提取日期

Python 正则表达式搜索内部带逗号的 float

php - 使用 php/mysql 保存所有输入(没有一一绑定(bind)参数)的正确方法是什么?

php - 从数组创建 XML

php - 拉维 4 : Route to controller when error occurred

ruby - 一个在 Ruby 上表现非常糟糕的简单正则表达式

用于删除重复词组的正则表达式