php:对给定字符串中的单词实例进行排序和计数 [英] php: sort and count instances of words in a given string

查看:72
本文介绍了php:对给定字符串中的单词实例进行排序和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我如何使用php计数字符串中每个单词的每个实例并将其循环输出:

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:

有4个快乐实例.

There are 4 instances of happy.

有3行实例.

有2个gin实例....

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使函数返回所有找到的单词的数组.

The 1 in str_word_count() makes the function return an array of all the found words.

要对条目进行排序,请使用 arsort() (它会保留键):

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
)

这篇关于php:对给定字符串中的单词实例进行排序和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆