Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page