Finding repeated words in PHP without specifying the word itself

前端 未结 1 746
名媛妹妹
名媛妹妹 2020-12-19 14:01

I\'ve been thinking about something for a project I want to do, I\'m not an advance user and I\'m just learning. Do not know if this is possible:

Suppose we have 100

相关标签:
1条回答
  • 2020-12-19 14:33
    function get_word_counts($phrases) {
       $counts = array();
        foreach ($phrases as $phrase) {
            $words = explode(' ', $phrase);
            foreach ($words as $word) {
              $word = preg_replace("#[^a-zA-Z\-]#", "", $word);
                $counts[$word] += 1;
            }
        }
        return $counts;
    }
    
    $phrases = array("It takes an ocean of water not to break!", "An ocean is a body of saline water, or so I am told.");
    
    $counts = get_word_counts($phrases);
    arsort($counts);
    print_r($counts);
    

    OUTPUT

    Array
    (
        [of] => 2
        [ocean] => 2
        [water] => 2
        [or] => 1
        [saline] => 1
        [body] => 1
        [so] => 1
        [I] => 1
        [told] => 1
        [a] => 1
        [am] => 1
        [An] => 1
        [an] => 1
        [takes] => 1
        [not] => 1
        [to] => 1
        [It] => 1
        [break] => 1
        [is] => 1
    )
    

    EDIT
    Updated to deal with basic punctuation, based on @Jack's comment.

    0 讨论(0)
提交回复
热议问题