Count word frequency in a text?

20,328

Your best bet are these:

Example

$words = 'A string with certain words occuring more often than other words.';
print_r( array_count_values(str_word_count($words, 1)) );

Output

Array
(
    [A] => 1
    [string] => 1
    [with] => 1
    [certain] => 1
    [words] => 2
    [occuring] => 1
    [more] => 1
    [often] => 1
    [than] => 1
    [other] => 1
)

marking CW because question is a duplicate of at least two other questions containing the same answer

Share:
20,328
YD8877
Author by

YD8877

Updated on March 18, 2020

Comments

  • YD8877
    YD8877 about 4 years

    Possible Duplicate:
    php: sort and count instances of words in a given string

    I am looking to write a php function which takes a string as input, splits it into words and then returns an array of words sorted by the frequency of occurence of each word.

    What's the most algorithmically efficient way of accomplishing this ?