TAGS :Viewed: 7 - Published at: a few seconds ago

[ PHP Count from File (Certain Words) ]

I have a strange problem to overcome, it simple but I cannot seem to find any solutions or get my head around this: I have a .html file that I want to read certain "words" and count how many of the certain words there are.

Thanks in advance

Just trying to get count of certain words to prevent glitches in my application.

Answer 1


You didn't specify if you're searching for multiple words, or just certain one, so I'm gonna go for multiple.

$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