【问题标题】:How to count all the words with special characters如何计算所有带有特殊字符的单词
【发布时间】:2020-06-06 05:09:35
【问题描述】:

我有一个关于字符串的问题,我想计算字符串中的所有字符。就像我有一个字符串

"Hello world & good morning. The date is 18.05.2016"

【问题讨论】:

    标签: php arrays string word-count


    【解决方案1】:

    您可以使用explode()将字符串转换为数组,然后使用count()函数计算数组的长度。

    echo count(explode(' ', "Hello world & good morning. The date is 18.05.2016"))
    

    【讨论】:

    • @user12195678 我的回答不适合您的问题吗?请让我知道。
    【解决方案2】:

    你可以试试这个代码。

    <?php
     $file = "C:\Users\singh\Desktop\Talkative Challenge\base_example.txt"; 
     $document = file_get_contents($file); 
     $return_array = preg_split("/[\s,]+/",$document);
     echo count($return_array);
     echo $document;
    ?>
    

    希望它会正常工作。

    【讨论】:

    • 这个简单的任务是不是 preg_split 有点重?
    • @Andreas 是的,它有点重,但它的工作很完美,这是我想要的。
    【解决方案3】:

    str_word_count 的第三个参数允许您设置额外的字符被计为单词:

    str_word_count($document, 0, '&.0..9');
    

    &amp;.0..9 表示将考虑&amp;.,范围从09

    【讨论】:

    • 我试过这个,但它给我的总字数为 8 但应该是 9。
    • 我已经调整了答案
    【解决方案4】:

    你可以用 substr_count 计算空格并加一个。

    echo substr_count($str, " ")+1;
    // 9
    

    https://3v4l.org/oJJkt

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多