PHP 从文本文件中搜索关键字,打印带有关键字的整行,然后计算打印的行数



我是PHP的新手,我试图用特定的关键字打印某些行,并使程序计算打印的行数。

这是我到目前为止所拥有的:

<?php
// LOOKS FOR "ERR:" IN THE LOG AND PRINTS THE WHOLE LINE.
$file = 'Sample.log';
$searchfor = 'ERR:';
$lines = 0;
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Lines found with the keyword " . """ . $searchfor . """ . "n";
echo implode("n", $matches[0]);
while (! feof($file))
}
else{
echo "No matches found";
}
?>

(代码最初是由 Lekensteyn 制作的,我只是根据自己的喜好对其进行了修改 - https://stackoverflow.com/users/427545/lekensteyn) 它使用关键字"ERR:"打印文本文件中的所有行,但我希望代码打印带有关键字"ERR:"(完成)的行,并在打印的行下方输出(计算打印的行数)"使用关键字 **\"ERR:**"打印的总行数:">

编辑:我尝试将其放在回声(内爆)下面: 回显"打印的总行数:" 。计数($matches); 但它只输出 1。帮助

这里本质上是一个可能有效的衬里:

$array  =   array_filter(array_map(function($v){
return (stripos($v,'ERR:') !== false)? $v : false; 
},array_filter(file('Sample.log',FILE_SKIP_EMPTY_LINES),function($v){
return (!empty(trim($v)));
})));
# This will implode the lines
echo (!empty($array))? implode('<br />',$array) : '';
# This will count the array
echo ((!empty($array))? count($array) : 0).' matches found.';
首先,它使用file()

使用新行将文件转换为数组,然后过滤可能存在的空行,然后使用array_map()进行迭代,然后在里面使用stripos()在每一行中搜索ERR:,然后返回匹配的(如果没有匹配,则返回false),然后array_filter()没有回调以删除所有带有false(空)的值。最后两行内爆剩余的数组,然后使用count()写入最终数组中有多少值。