Specify how many times some words appear in strings in PHP

I was wondering how I can find multiple words and get the results, how many are counted in the file. I've already integrated it where it counts all lines so that it checks every word in every line. But I am having trouble counting how many times one of the words is in a string.

Let's say that a text file looks something like this:

cars have wheels
you can drive cars
1337 is Leet
the beauty of cars
too much cars
something else
good breakfast could be eggs
eggs does not smell good
flying cars could be the future

      

And I want the array to look like this:

words = cars,eggs,1337

array{
    "cars" => 5,
    "eggs" => 2,
    "1337" => 1
}

      

And I already installed this code:

$words = explode(',', 'word1,word2,word3');

$handle = fopen('/path/to/file.txt', "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        foreach ($words as $value => $number) {
            if (strpos($line, $value) !== false) {
                $words[$number] = $words[$number] + 1;
            }
        }
    }

    fclose($handle);
}

var_dump($words)

      

this code outputs:

array(1) { 
    [0]=> array(3) { 
        [0]=> string(10) "cars" 
        [1]=> string(9) "eggs" 
        [2]=> string(10) "1337" 
    } 
}

      

I know I don't have to do this for every line, but this is more code that I removed from this question (including counting and echoing in a specific way). And it looks like I'm doing it wrong in the part where I have to add +1 to each word, but I just don't understand how to handle arrays correctly.

+3


source to share





All Articles