Link to home
Start Free TrialLog in
Avatar of ray-solomon
ray-solomonFlag for United States of America

asked on

Getting most common words from array

I need a php script to find repeat words and output it.

Example text submitted from a textarea box:

drink energy
juice drink
hot cakes
fruit baskets
peanut butter and jelly
energy juice
fine wine
berry jelly

should return:

drink energy
juice drink
peanut butter and jelly
energy juice
berry jelly

because energy, juice, jelly and drink were most common, it should return those values from an array and also count it.


Avatar of TeRReF
TeRReF
Flag of Netherlands image

Something like this should work:
<?php

        $words = array('drink energy', 'juice drink', 'hot cakes', 'fruit baskets', 'peanut butter and jelly', 'energy juice', 'fine wine', 'berry jelly');
        $s = implode(' ', $words);
        $singlewords = array_unique(explode(' ', $s));
        //print_r($singlewords);
        //print($s);
        foreach($singlewords as $word) {
                preg_match_all('/'.$word.'/i', $s, $matches);
                $wordcount[$word] = count($matches[0]);
        }
        arsort($wordcount);
        $final_array = array();
        foreach($wordcount as $word=>$count) {
                foreach($words as $match) {
                        if (stripos($match, $word) !== false && !in_array($match, $final_array))
                                $final_array[] = $match;
                }
        }
        print_r($final_array);


?>
Avatar of ray-solomon

ASKER

Thanks TeRRef, but I get this error message:
Fatal error: Call to undefined function: stripos() in /home/...
CHange this line:
                      if (stripos($match, $word) !== false && !in_array($match, $final_array))
to
                      if (strpos(strtolower($match), strtolower($word)) !== false && !in_array($match, $final_array))
Here is what the array contains:

Array ( [0] => drink energy [1] => juice drink [2] => peanut butter and jelly [3] => berry jelly [4] => energy juice [5] => fine wine [6] => fruit baskets [7] => hot cakes )


it should look like this:

Array ( [0] => drink energy [1] => juice drink [2] => peanut butter and jelly [3] => berry jelly [4] => energy juice )


because:
fine wine, fruit baskets and hot cakes do not contain any words that have been repeated two or more times in the array.

Hope that makes sense. BTW, thanks for helping me so far.
Is there a way to make it output the most common words like I showed in my original question?
ASKER CERTIFIED SOLUTION
Avatar of TeRReF
TeRReF
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you! Awsome.
You're welcome.