【问题标题】:How to check how many times a word appears in a txt file in php?如何检查一个单词在php的txt文件中出现了多少次?
【发布时间】:2015-02-19 15:03:32
【问题描述】:

如何查看一个单词在 txt/log 文件中出现的次数?

例如:

110.90.252.35 -- [2007-05-01 10:10:55] "GET 文章/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]“获取文章/非/a/页面 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);
  ?>

【问题讨论】:

    标签: php logfile


    【解决方案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";
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 2022-12-03
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        相关资源
        最近更新 更多