php:对给定字符串中的单词实例进行排序和计数

标签 php

我需要帮助对字符串中的单词实例进行排序和计数。

假设我有一个单词集:

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/

相关文章:

php - 使用 openssl_private_decrypt 解密将不起作用,因为文本正在存储撇号

php - Wordpress 只在 front-page.php 上显示最近的帖子

php - 日期时间数据类型在比较中总是忽略时间

php - 单击提交按钮后重定向到另一个页面并传递变量

php - 在 Windows 命令提示符 (cmd) 中运行 .php 文件

php - 如何将additionProvider与存储库功能一起使用?

javascript - 验证 NoCaptcha ReCaptcha

php - Mysql插入文本语句,内容中带引号

php - 使行不同并且重复行值总计

php - 从 MySQL 获取数组到 android