【发布时间】:2018-07-08 09:23:33
【问题描述】:
我想获取日志错误文件中的每个错误。
所以如果文件包含:
[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>';
}
但这会获取每一行,所以第二行将存储在几个变量中,我想在一个变量中获取每个错误。
这可能吗?
【问题讨论】:
-
Warning: preg_split() expects parameter 2 to be string, array given, $contents 是一个包含文本行的数组 -
我把它改成
$contents = file_get_contents();然后$contents = preg_split();,但是它返回一个数组,其中一个值是整个文本 -
好吧,可能我放错了
^,试试'~\s+(?=^\[\d{2}-\w{3}-\d{4} \d+(?::\d{2}){2} \w{3}])~m'。您仍然可以逐行读取文件,检查是否有行preg_match('~^\[\d{2}-\w{3}-\d{4} \d+(?::\d{2}){2} \w{3}]~', $line)并将这些行添加到临时变量中,然后再找到与该模式或字符串结尾匹配的另一行。 -
我尝试了
preg_split('/\s+(?=^\[\d{2}-\w{3}-\d{4} \d+(?::\d{2}){2} \w{3}])/m', $contents);,它成功了,它到底会匹配什么?
标签: php regex wordpress error-handling filesystems