如何检查txt /日志文件中单词出现的次数?
例如:
110.90.252.35 - [2007-05-01 10:10:55]"获取文章/ learn_PHP_basics HTTP / 1.0" 200 11178" MSIE 7.0"
23.18.147.37 - [2007-05-01 10:54:33]"获取/ contact.php HTTP / 1.0" 200 4326" Mozilla / 4.0"
250.69.170.251 - [2007-05-01 11:38:11]"获取文章/不/ a / page HTTP / 1.0" 404 0" Mozilla / 4.0"
从日志文件中提取了三条陈述,我试图查看“'”文章中的多少次'出现在此文件中。我尝试过使用数组,然后计算它出现的次数,但到目前为止还没有计算出来。那还有别的办法。
我的代码:
enter code here
$mayFile = "C:\Users\Elsa\Desktop\TMA\may.log";
$myfile = fopen("may.log", "r");
$lines = count(file("may.log"));
echo "There are $lines lines";
while(!feof($myfile)) {
$getFile = fgets($myfile);
$parts = explode(" ",$getFile);
$frequency = array_count_values($parts);
print_r($parts);
$items = array_count_values($parts);
}
fclose($myfile);
fclose($myfile1);
?>
答案 0 :(得分:1)
答案 1 :(得分:1)
它可以更轻松地完成:
$filename = "C:\Users\Elsa\Desktop\TMA\may.log";
$searchFor = "articles";
$fileContent = file_get_contents($filename);
$count = substr_count($fileContent, $searchFor);
echo "'$filename' contains '$searchFor' $count times";