Count all word including numbers in a php string

前端 未结 8 1171
梦谈多话
梦谈多话 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:59

    Just some improvement your solution

    function stringWordNumberCount($text){
        if (!$text) {
            return 0;
        }
    
        //Clean the text to remove special character
        $text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));
    
        //Remove continus space on text
        $text = trim( preg_replace('/\s+/', ' ',$text));
    
        //count space
        return count(explode(' ', $text));
    
    }
    

提交回复
热议问题