PHP 从文件中计数(某些单词)

PHP Count from File (Certain Words)

我有一个奇怪的问题要克服,它很简单,但我似乎无法找到任何解决方案或解决这个问题:我有一个 .html 文件,我想阅读某些 "words" 并统计其中有多少个单词。

提前致谢

只是尝试计算某些单词的数量以防止我的应用程序出现故障。

你没有指定你是在搜索多个词,还是只搜索某个词,所以我要搜索多个词。

$count = 0; //Create a variable for counting
$contents = file_get_contents("yourfile.html"); //Load your file into a string
$words = array('word1', 'word2', 'word3');  //Specify which words you want to search for

foreach($words as $word) {  //For each word in array do
$place = strpos($contents, $word); //Get the position of searched word
if (!empty($place)) { //if a word has been found, increment the count variable
    $count++;
} 
}
echo 'Number of filtered words: ' . $count; //Print out the number of words