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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题