代码之家  ›  专栏  ›  技术社区  ›  superUntitled

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

php
  •  16
  • superUntitled  · 技术社区  · 14 年前

    假设我收集了一些单词:

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

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

    There are $count instances of $word
    

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

    有4个快乐的例子。

    有3个线条实例。

    杜松子酒有两个例子。。。。

    2 回复  |  直到 4 年前
        1
  •  53
  •   Felix Kling    14 年前

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

    要对条目进行排序,请使用 arsort()

    arsort($words);
    print_r($words);
    
    Array
    (
        [happy] => 4
        [lines] => 3
        [pear] => 2
        [rock] => 1
        [gin] => 1
        [beautiful] => 1
    )
    
        2
  •  6
  •   Tatu Ulmanen    14 年前

    试试这个:

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