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

php
2022-08-30 22:38:20

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

假设我有一个关于单词的集合:

快乐美丽快乐线条梨杜松子酒快乐线条摇滚快乐线条梨

我如何使用php来计算字符串中每个单词的每个实例,并在循环中输出它:

There are $count instances of $word

因此,上面的循环将输出:

有4个快乐的例子。

有 3 个行实例。

杜松子酒有2个实例.


答案 1

使用 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
)

in 使函数返回所有找到的单词的数组。1str_word_count()

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

arsort($words);
print_r($words);

Array
(
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [rock] => 1
    [gin] => 1
    [beautiful] => 1
)

答案 2

试试这个:

$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. 

推荐