php 如何查看一个单词在txt文件中出现了多少次?

How to check how many times a word appears in a txt file in php?

如何检查一个词在 txt/log 文件中出现了多少次?

例如:

110.90.252.35 -- [2007-05-01 10:10:55] "GET articles/learn_PHP_basics HTTP/1.0" 200 11178 "MSIE 7.0"

23.18.147.37 -- [2007-05-01 10:54:33] "GET about/contact.php HTTP/1.0" 200 4326 "Mozilla/4.0"

250.69.170.251 -- [2007-05-01 11:38:11] "GET articles/not/a/page HTTP/1.0" 404 0 "Mozilla/4.0"

从日志文件中提取的三个语句,我试图查看单词 'articles' 在该文件中出现了多少次。我试过使用一个数组,然后计算它出现的次数,但到目前为止还没有成功。那么有没有其他办法呢

我的代码:

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);
  ?>

应该有一个 php 函数:

http://php.net/manual/en/function.substr-count.php

可以更简单地完成:

$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";