Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

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

I need help sorting and counting instances of the words in a string.

Lets say I have a collection on words:

happy beautiful happy lines pear gin happy lines rock happy lines pear

How could I use php to count each instance of every word in the string and output it in a loop:

There are $count instances of $word

So that the above loop would output:

There are 4 instances of happy.

There are 3 instances of lines.

There are 2 instances of gin....

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...