php:对给定字符串中的单词实例进行排序和计数
我需要帮助排序和计算字符串中的单词实例 假设我有一个单词集: 快乐美丽快乐线条梨子杜松子酒快乐线条摇滚快乐线条梨子 如何使用php计算字符串中每个单词的每个实例并将其输出到循环中:php:对给定字符串中的单词实例进行排序和计数,php,Php,我需要帮助排序和计算字符串中的单词实例 假设我有一个单词集: 快乐美丽快乐线条梨子杜松子酒快乐线条摇滚快乐线条梨子 如何使用php计算字符串中每个单词的每个实例并将其输出到循环中: There are $count instances of $word 这样,上述循环将输出: 有4个快乐的例子 有3个线的实例 杜松子酒有两个例子 结合使用和: 给予 str\u word\u count()中的1使函数返回所有找到的单词的数组 要对条目进行排序,请使用(保留键): 试试这个: $words =
There are $count instances of $word
这样,上述循环将输出:
有4个快乐的例子
有3个线的实例
杜松子酒有两个例子
结合使用和:
给予
str\u word\u count()
中的1
使函数返回所有找到的单词的数组
要对条目进行排序,请使用(保留键):
试试这个:
$words = explode(" ", "happy beautiful happy lines pear gin happy lines rock happy lines pear");
$result = array_combine($words, array_fill(0, count($words), 0));
foreach($words as $word) {
$result[$word]++;
}
foreach($result as $word => $count) {
echo "There are $count instances of $word.\n";
}
结果:
There are 4 instances of happy.
There are 1 instances of beautiful.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock.
我怎么能把这个和重音词连用呢?例子:太简单了!;)谢谢@syfantid是的,你说得很好,不需要其他答案;)
arsort($words);
print_r($words);
Array
(
[happy] => 4
[lines] => 3
[pear] => 2
[rock] => 1
[gin] => 1
[beautiful] => 1
)
$words = explode(" ", "happy beautiful happy lines pear gin happy lines rock happy lines pear");
$result = array_combine($words, array_fill(0, count($words), 0));
foreach($words as $word) {
$result[$word]++;
}
foreach($result as $word => $count) {
echo "There are $count instances of $word.\n";
}
There are 4 instances of happy.
There are 1 instances of beautiful.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock.