我在一个文本文件中有一堆日志记录,我尝试使用pregmatch在冒号后直接提取信息,例如我有:
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo]操作系统架构:64位 04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo]操作系统Service Pack:Service Pack 1
我有这个代码,它适用于以前使用的类似的代码,但我是一个正则表达式的新手,它似乎没有在这里工作:
preg_match('/Operating System Architecture: (.+?)<br>/', $body, $os_bit);
preg_match('/Operating System Service Pack: (.+?)<br>/', $body, $os_service_pack);
但是当我回应这个
echo $os_bit[1];
echo $os_service_pack[1];
我没有得到任何回报
正文是一个巨大的日志文件,所以我只是将相关信息的片段拉到上面,所以希望这足够了。其中大约8个都在新线上,如上面的例子,所以如果我得到一个病,能够得到所有
答案 0 :(得分:1)
您使用的是preg_match
日志文件吗?在这种情况下,行尾不应该是<br>
,而应该只是换行符(\n
)。由于除非您最后使用/s
,否则点通常与换行符不匹配,请尝试:
preg_match('/Operating System Architecture: (.*)/', $body, $os_bit);
preg_match('/Operating System Service Pack: (.*)/', $body, $os_service_pack);
另请注意,$os_bit
和$os_service_pack
将是数组,因此要调试您可能要使用print_r($os_bit);
答案 1 :(得分:1)
以下是我根据提供的数据量得出的结果:
<?php
$body = "
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Architecture: 64 bits
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Service Pack: Service Pack 1
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Architecture: 64 bits
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Service Pack: Service Pack 1
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Architecture: 64 bits
04:28:17.409 [Main:1 - Bootstrapper.LogSystemInfo] Operating System Service Pack: Service Pack 1";
preg_match_all('/(Operating System Architecture:.*)(\n|$)/i', $body, $os_bit);
preg_match_all('/(Operating System Service Pack:.*)(\n|$)/i', $body, $os_service_pack);
print_r($os_bit[1]);
print_r($os_service_pack[1]);
然后产生这个:
Array
(
[0] => Operating System Architecture: 64 bits
[1] => Operating System Architecture: 64 bits
[2] => Operating System Architecture: 64 bits
)
Array
(
[0] => Operating System Service Pack: Service Pack 1
[1] => Operating System Service Pack: Service Pack 1
[2] => Operating System Service Pack: Service Pack 1
)