Count all word including numbers in a php string

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

    You can always split your string by whitespace and count the results:

    $res = preg_split('/\s+/', $input);
    $count = count($res);
    

    With your string

    "The example number 2 is a bad example it will not 
    count numbers  and punctuations !!"
    

    This code will produce 16.

    The advantage of using this over explode(' ', $string) is that it will work on multi-line strings as well as tabs, not just spaces. The disadvantage is that it's slower.

提交回复
热议问题