PHP str_word_count() Function
The PHP str_word_count() function counts the number of words in a given string. If the format parameter is not specified, then the function returns an integer representing the number of words found. If the format parameter is specified, then it returns an array, content of which is dependent on the format.
For this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with ' and - characters. Please note that multibyte locales are not supported.
Syntax
str_word_count(string, format, characters)
Parameters
string |
Required. Specify the string to check. |
format |
Optional. Specify the return value of this function. The possible values are:
|
characters |
Optional. Specify a list of additional characters which will be considered as 'word'. |
Return Value
Returns an array or an integer, depending on the format chosen.
Example: str_word_count() example
The example below shows the usage of str_word_count() function.
<?php $str = "To be, or not to be, that is the question."; echo "Number of words: ",str_word_count($str)."\n"; echo "Number of words: ",str_word_count($str, 0)."\n"; ?>
The output of the above code will be:
Number of words: 10 Number of words: 10
Example: using format parameter
The example below illustrates on using format parameter with this function.
<?php $str = "Hello fri3nd, you're looking good today!"; //using format parameter print_r(str_word_count($str, 1)); print_r(str_word_count($str, 2)); //using third paramater to include additional //characters which will be considered as 'word' print_r(str_word_count($str, 1, 'àáãç3')); ?>
The output of the above code will be:
Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [21] => looking [29] => good [34] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today )
❮ PHP String Reference