/** * Finds All of the keywords (words this appear most) on Param $str * and return them in order of the most occurrences to less occurrences. * @param string $str The string to search for the keywords. * @param int $minWordLen [OPTIONAL] The minimun length (number of chars) of a word to be considered a keyword. * @param int $minWordOccurrences [OPTIONAL] The minimun number of times a word have to appear * on Param $STR To is considered a keyword. * @param boolean $asArray [optional] Specifies if the function returns a string with the * Keywords separated by a comma ($asArray = false) or a keywords array ($asArray = True). * @return mixed A string with keywords separated with commas if Param $asArray is true, * An array with the keywords otherwise. */ function Extract_keywords ($str, $minWordLen = 3, $minWordOccurrences = 2, $asArray = False) { function Keyword_count_sort ($first, $sec) { return $sec [1]-$first [1]; } $str = Preg_replace ('/[^\\w0-9]/', ', $str); $str = Trim (preg_replace ('/\s+/', ' ', $str)); $words = Explode (' ', $str); $keywords = Array (); while (($c _word = Array_shift ($words))!== null) { if (strlen ($c _word) <= $minWordLen) continue; $c _word = strtolower ($c _word); if (array_key_exists ($c _word, $keywords)) $keywords [$c _word][1]++; else $keywords [$c _word] = Array ($c _word, 1); } Usort ($keywords, ' keyword_count_sort '); $final _keywords = Array (); foreach ($keywords as $keyword _det) { if ($keyword _det[1] < $minWordOccurrences) break; Array_push ($final _keywords, $keyword _det[0]); } Return $asArray? $final _keywords:implode (', ', $final _keywords); } How to use Basic Lorem ipsum text to extract the keywords $text = " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget ipsum ut lorem laoreet porta a non libero. Vivamus in Tortor metus. Suspendisse Potenti. Curabitur Metus nisi, adipiscing eget placerat suscipit, suscipit Vitae Felis. The Integer EU odio enim, sed dignissim lorem. In Fringilla molestie justo, vitae varius risus lacinia AC. Nulla porttitor Justo a lectus iaculis ut vestibulum magna Egestas. Ut sed purus et nibh cursus fringilla at ID purus. "; Echoes:lorem, Suscipit, Metus, Fringilla, Purus, Justo, Eget, Vitae, Ipsum, Curabitur, adipiscing echo Extract_keywords ($text); |