Count all word including numbers in a php string

前端 未结 8 1198
梦谈多话
梦谈多话 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 18:00

    I know the question is old, Still i m sharing the fix i have adopt for this.

    $str ="Hello world !";
    // you can include allowed special characters  as third param.
    print_r(str_word_count($str, 1, '!'));
    

    code output is

    Array ( [0] => Hello [1] => world [2] => ! )
    

    if you want to include more words u can specify as third param.

    print_r(str_word_count($str, 1, '0..9.~!@#$%^&*()-_=+{}[]\|;:?/<>.,'));
    

    from 0..9. will include all numbes, and other special characters are inserted individually.

    0 讨论(0)
  • 2021-02-15 18:01

    The following using count() and explode(), will echo:

    The number 1 in this line will counted and it contains the following count 8
    

    PHP:

    <?php
    
    $text = "The number 1 in this line will counted";
    
    $count = count(explode(" ", $text));
    
    echo "$text and it contains the following count $count";
    
    ?>
    

    Edit:

    Sidenote:
    The regex can be modified to accept other characters that are not included in the standard set.

    <?php
    
    $text = "The numbers   1  3 spaces and punctuations will not be counted !! . . ";
    
    $text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));
    
    $text = preg_replace('/\s+/', ' ', $text);
    
    
    // used for the function to echo the line of text
    $string = $text;
    
        function clean($string) {
    
           return preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);
    
        }
    
    echo clean($string);
    
    echo "<br>";
    
    echo "There are ";
    echo $count = count(explode(" ", $text));
    echo " words in this line, this includes the number(s).";
    
    echo "<br>";
    
    echo "It will not count punctuations.";
    
    ?>
    
    0 讨论(0)
提交回复
热议问题