我需要帮助对字符串中的单词实例进行排序和计数。
假设我有一个单词集:
happy beautiful happy lines pear gin happy lines rock happy lines pear
我如何使用 php 来计算字符串中每个单词的每个实例并在循环中输出它:
There are $count instances of $word
这样上面的循环会输出:
There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of gin....
最佳答案
使用 str_word_count()
的组合和 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);
给予
Array
(
[happy] => 4
[beautiful] => 1
[lines] => 3
[pear] => 2
[gin] => 1
[rock] => 1
)
str_word_count()
中的 1
使函数返回所有找到的单词的数组。
要对条目进行排序,请使用 arsort()
(它保留 key ):
arsort($words);
print_r($words);
Array
(
[happy] => 4
[lines] => 3
[pear] => 2
[rock] => 1
[gin] => 1
[beautiful] => 1
)
关于php:对给定字符串中的单词实例进行排序和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744918/