/** * Finds all of the keywords (words that appear most) on param $ str * And return them in order of 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 has to appear * On param $ str to be considered a keyword. * @ Param boolean $ asArray [optional] Specifies if the function returns a string with * 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. 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 ); |