【发布时间】:2016-06-01 09:07:54
【问题描述】:
我有一个具有这种结构的文件:
[19-02-2016 16:57:17.104504] [info] system done.
0: array(
'ID' => 'john foo'
)
[19-02-2016 16:57:17.110482] [info] transaction done.
0: array(
'ID' => 'john foo'
)
现在我想将文件内容解析为 json,实际上一切正常:
<?php
$file = 'test.log';
$content = array();
$content["trace"] = array();
$input = file_get_contents('test.log');
preg_match_all('/\[(.*)\][\s]*?\[(.*?)\][\s]*?(.*)[\s][^\']*\'ID\'[ ]*=>[ ]*\'(.*)\'/', $input, $regs, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($regs[0]); $i++) {
$content['trace'][] = array(
'date' => $regs[1][$i],
'type' => trim($regs[2][$i]),
'message' => trim($regs[3][$i]),
'ID' => trim($regs[4][$i]),
);
}
// return $content;
echo '<pre>'; print_r($content); echo '</pre>'; // For testing only
$content = json_encode($content); // For testing only
echo '<pre>' . $content . '</pre>'; // For testing only
现在这段代码返回这个结果:
{
"trace":[
{
"date":"19-02-2016 16:57:17.104504",
"type":"info",
"message":"system done.",
"ID":"john foo"
},
{
"date":"19-02-2016 16:57:17.110482",
"type":"info",
"message":"transaction done.",
"ID":"john foo"
}
]
}
问题是,如果我有这种情况(在文件中):
[19-02-2016 16:57:17.104504] [info] system done.
[19-02-2016 16:57:17.110482] [info] transaction done.
0: array(
'ID' => 'john foo'
)
我没有得到任何结果,因为正则表达式失败。这是因为第一行没有任何数组,我该如何解决这种情况?
CODEHART 代码:
preg_match_all('\[(.*)\][\s]*?\[(.*?)\][\s]*?(.*)[\s.]([^\']*\'ID\'[ ]*=>[ ]*\'(.*)\')?', $fh, $regs, PREG_PATTERN_ORDER);
for($i = 0; $i < count($regs[0]); $i++)
{
var_dump($regs);
$content['trace'][] = array(
'date' => $regs[1][$i],
'type' => trim($regs[2][$i]),
'message' => trim($regs[3][$i]),
'ID' => trim($regs[4][$i]),
);
}
我从 var_dump 得到 null
【问题讨论】:
-
我最初的想法是,您将不得不更改逻辑以首先检查每一行的日期,因为这是新条目的标记。也许在
\r\n[上拆分文件以将每个条目分解为一个数组元素。然后对于每个数组元素,解析你需要的部分。 -
该数组本质上是用户生成的跟踪日志,这有助于我识别系统上已生成事务的用户。现在,如果我不传递任何上下文,问题就会发生。
-
@Sandokan,你还没有添加开头和结尾
/,请更新你的代码,虽然我也会在几分钟内确认 -
@Sandokan,检查更新后的答案,现在您也不必更新 for 循环,只需对索引号 4 进行相关检查