首页  >  文章  >  后端开发  >  如何在 PHP 中对字符串中出现的单词进行计数和排序?

如何在 PHP 中对字符串中出现的单词进行计数和排序?

Susan Sarandon
Susan Sarandon原创
2024-10-21 10:26:02230浏览

How to Count and Sort Word Occurrences in a String in PHP?

对字符串中出现的单词进行排序和计数

问题陈述:

您将被呈现包含各种单词的字符串。当前的任务是确定字符串中每个单词的出现频率,并以有组织的方式显示出来。

使用 PHP 的字数统计功能的解决方案:

PHP 提供str_word_count() 函数,它将字符串拆分为单个单词的数组。通过将此函数与 array_count_values() 函数结合使用,我们可以有效地统计每个单词的出现次数。

<code class="php">$str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear ';
$words = array_count_values(str_word_count($str, 1));</code>

参数为 1 的 str_word_count() 函数可确保返回单词数组。随后,array_count_values() 获取该数组并将其转换为关联数组,其中每个唯一单词作为键,其值代表出现的次数。

可以使用 arsort( ) 函数按频率降序列出单词:

<code class="php">arsort($words);</code>

要在循环中显示排序结果,我们可以迭代排序数组并打印每个单词的计数:

<code class="php">foreach ($words as $word => $count) {
    echo "There are $count instances of $word.\n";
}</code>

这将产生类似于您提供的输出:

There are 4 instances of happy.
There are 3 instances of lines.
There are 2 instances of pear.
There are 1 instances of gin.
There are 1 instances of rock.
There are 1 instances of beautiful.

以上是如何在 PHP 中对字符串中出现的单词进行计数和排序?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn