doubi6898 2019-05-18 01:20
浏览 94
已采纳

使用PHP中的str_word_count将数字计为单独的单词

I am trying to use str_word_count to count the number of words in a message.

$wordcount = str_word_count($message,0,'0123456789');

I can pretty much be guaranteed that there will just be words, numbers, and spaces in there. The message is the result of an encoded speech to text message.

One thing I am struggling with is getting it to properly return the right number of words. I need each digit to be counted as its own word. Thus "4 5 6" is 3 words and "456" is also 3 words. "FOUR" is one word and "FOUR 44" is 3 words, etc.

The documentation for this function says I ought to be able to do this by specifying characters to count as words as the third argument, which I have done. However, an entire "block" of digits is still counted as only one word. I tried adding spaces between the digits but that visually triggered a syntax error in Notepad++ and blew up my whole PHP page, basically.

I thought about filtering the string for digits and then adding its length to the word count, but then I am double counting some digits for sure... and that's just messy!

Is there any way I can do this natively with str_word_count?

  • 写回答

2条回答 默认 最新

  • duanlan8763 2019-05-18 01:28
    关注

    One way to work around this is to use preg_replace first to split your strings of digits into individual digits, and then count the words. For example:

    $message = "I have 123 chickens";
    $message = preg_replace('/\s*(\d)/', ' $1', $message);
    $wordcount = str_word_count($message, 0, '0123456789');
    echo $wordcount;
    

    Output

    6
    

    Demo on 3v4l.org

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?