Use a combination of
str_word_count()
and array_count_values()
:$str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear ';
$words = array_count_values(str_word_count($str, 1));
print_r($words);
gives
Array
(
[happy] => 4
[beautiful] => 1
[lines] => 3
[pear] => 2
[gin] => 1
[rock] => 1
)
The
1
in str_word_count()
makes the function return an array of all the found words.
To sort the entries, use
arsort()
(it preserves keys):arsort($words);
print_r($words);
Array
(
[happy] => 4
[lines] => 3
[pear] => 2
[rock] => 1
[gin] => 1
[beautiful] => 1
)
http://stackoverflow.com/questions/2984786/php-sort-and-count-instances-of-words-in-a-given-string
No hay comentarios:
Publicar un comentario