我想在日志错误文件中获取每个错误。
因此,如果文件包含:
[08-Jul-2018 08:12:04 UTC] PHP Fatal error: Call to undefined method DateTime::fomat() in C:\xampp\htdocs\wordpress\wp-content\themes\theme\index.php on line 44
[08-Jul-2018 08:22:22 UTC] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.table' doesn't exist' in C:\xampp\htdocs\wordpress\wp-content\themes\theme\index.php:37
Stack trace:
#0 C:\xampp\htdocs\wordpress\wp-content\themes\news_theme\index.php(37):
PDOStatement->execute()
#1 C:\xampp\htdocs\wordpress\wp-includes\template-loader.php(74):
include('C:\\xampp\\htdocs...')
#2 C:\xampp\htdocs\wordpress\wp-blog-header.php(19):
require_once('C:\\xampp\\htdocs...')
#3 C:\xampp\htdocs\wordpress\index.php(17): require('C:\\xampp\\htdocs...')
#4 {main}
thrown in C:\xampp\htdocs\wordpress\wp-content\themes\theme\index.php on line 37
这是两个错误,但是其中一个错误很长并且占用多于一行。
我想在变量中获取它们的每个错误。
我试过了:
$contents = file(get_template_directory().'/errors.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($contents as $key => $content) {
echo $key . $content . '<br>';
}
但这得到每一行,因此第二行将存储在多个变量中,而我想将每个错误都存储在一个变量中。
那可能吗?
最佳答案
使用file_get_contents
将文件作为单个字符串读取,然后使用
$splits = preg_split('/\s+(?=^\[\d{2}-\w{3}-\d{4} \d+(?::\d{2}){2} \w{3}])/m', $contents);
模式匹配
\s+
-1+个空格,后跟... (?=^\[\d{2}-\w{3}-\d{4} \d+(?::\d{2}){2} \w{3}])
-当前位置右侧的正向超前查询,要求:^
-行的开头(由于m
修饰符)\[
-一个[
char \d{2}-\w{3}-\d{4}
-2位数字,-
,3个字符字符,-
,4位数字
-空格\d+
-1个以上数字(?::\d{2}){2}
-2次出现:
和2位数字(与:\d{2}:\d{2}
相同)
-空格\w{3}
-3个字字符(字母,数字或_
)]
-一个]
字符。 参见regex demo。
关于php - 如何从错误日志文件中获取每个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230562/