Name

str_word_count()

Synopsis

    mixed str_word_count ( string str [, int count_type [, string char_list]] )

The str_word_count() function returns the number of words in a string. You can pass a second parameter to str_word_count() to make it do other things, but if you only pass the string parameter by itself, then it returns the number of unique words that were found in the string. If you pass 1 as the second parameter, it will return an array of the words found; passing 2 does the same, except the key of each word will be set to the position where that word was found inside the string.

Here are examples of the three options:

    $str = "This is a test, only a test, and nothing but a test.";
    $a = str_word_count($str, 1);
    $b = str_word_count($str, 2);
    $c = str_word_count($str);
    print_r($a);
    print_r($b);
    echo "There are $c words in the string\n";

That should output the following:

    Array ( [0] => This [1] => is [2] => a [3] => test [4]
    => only [5] => a [6] => test [7] => and [8] =>
    nothing [9] => but [10] => a [11] => test )

    Array ( [0] => This [5] => is [8] => a [10] => test [16]
    => only [21] => a [23] => test [29] => and [33] =>
    nothing [41] => but [45] => a [47] => test )

    There are 12 words in the string

In the first line, the array keys are irrelevant, but the array values are the list of the words found—note that the comma and period are not in there, as they are not considered words. In the second line, the array keys mark where the first letter of the word in the value was found, thus ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.