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

sup*_*led 17 php

我需要帮助排序和计算字符串中单词的实例.

可以说我有一个关于单词的集合:

快乐美丽的快乐线梨杜松子酒快乐线岩石快乐线梨

我怎么能用php来计算字符串中每个单词的每个实例并将它输出到循环中:

There are $count instances of $word
Run Code Online (Sandbox Code Playgroud)

这样上面的循环就会输出:

有4个快乐的例子.

有3个线条实例.

有2个杜松子酒的例子....

Fel*_*ing 52

使用的组合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);
Run Code Online (Sandbox Code Playgroud)

Array
(
    [happy] => 4
    [beautiful] => 1
    [lines] => 3
    [pear] => 2
    [gin] => 1
    [rock] => 1
)
Run Code Online (Sandbox Code Playgroud)

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

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

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

Array
(
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [rock] => 1
    [gin] => 1
    [beautiful] => 1
)
Run Code Online (Sandbox Code Playgroud)


Tat*_*nen 5

试试这个:

$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";
}
Run Code Online (Sandbox Code Playgroud)

结果:

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. 
Run Code Online (Sandbox Code Playgroud)