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

时间:2010-06-06 15:40:58

标签: php

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

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

  幸福美丽幸福的线条梨杜松子酒幸福线条摇滚幸福线条梨

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

There are $count instances of $word

以便上面的循环输出:

  

有4个快乐的例子。

     

有三行。

     

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

2 个答案:

答案 0 :(得分:51)

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

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

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

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

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

答案 1 :(得分: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";
}

结果:

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.