Count how often the word occurs in the text in PHP

后端 未结 4 558
说谎
说谎 2020-12-18 01:44

In php I need to Load a file and get all of the words and echo the word and the number of times each word shows up in the text, (I also need them to show up in descending or

4条回答
  •  隐瞒了意图╮
    2020-12-18 02:21

    Here's an example:

    $text = "A very nice únÌcÕdë text. Something nice to think about if you're into Unicode.";
    
    // $words = str_word_count($text, 1); // use this function if you only want ASCII
    $words = utf8_str_word_count($text, 1); // use this function if you care about i18n
    
    $frequency = array_count_values($words);
    
    arsort($frequency);
    
    echo '
    ';
    print_r($frequency);
    echo '
    ';

    The output:

    Array
    (
        [nice] => 2
        [if] => 1
        [about] => 1
        [you're] => 1
        [into] => 1
        [Unicode] => 1
        [think] => 1
        [to] => 1
        [very] => 1
        [únÌcÕdë] => 1
        [text] => 1
        [Something] => 1
        [A] => 1
    )
    

    And the utf8_str_word_count() function, if you need it:

    function utf8_str_word_count($string, $format = 0, $charlist = null)
    {
        $result = array();
    
        if (preg_match_all('~[\p{L}\p{Mn}\p{Pd}\'\x{2019}' . preg_quote($charlist, '~') . ']+~u', $string, $result) > 0)
        {
            if (array_key_exists(0, $result) === true)
            {
                $result = $result[0];
            }
        }
    
        if ($format == 0)
        {
            $result = count($result);
        }
    
        return $result;
    }
    

提交回复
热议问题