Count all word including numbers in a php string

前端 未结 8 1197
梦谈多话
梦谈多话 2021-02-15 17:01

To count words in a php string usually we can use str_word_count but I think not always a good solution

good example:

$var =\"Hello world!\";
echo str_         


        
8条回答
  •  难免孤独
    2021-02-15 17:54

    You may also use the below code it's working for me.

        function get_num_of_words($string) {
            $string = preg_replace('/\s+/', ' ', trim($string));
            $words = explode(" ", $string);
            return count($words);
        }
    
        $string="php string word count in simple way";
        echo $count=get_num_of_words($string);
    

    The result will be 7

提交回复
热议问题