str_word_count()

str_word_count() — Return information about words used in a string.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

Signature

str_word_count(string $string, int $format = 0, ?string $characters = null): array|int

Parameters

ParameterTypeWhat it takes
$stringstringThe string
$formatintSpecify the return value of this function. The current supported values are: 0 - returns the number of words found 1 - returns an array containing all the words found inside the string 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself
$characters?stringA list of additional characters which will be considered as 'word'

Return value

Returns an array or an integer, depending on the format chosen.

Example

A runnable snippet:

$str = "Hello fri3nd, you're looking good today!"; print_r(str_word_count($str, 1)); print_r(str_word_count($str, 2)); print_r(str_word_count($str, 1, 'àáãç3')); echo str_word_count($str);

Output:

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 [28] => looking [45] => good [50] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7

Changelog

VersionChange
8.0.0Now throws a ValueError if format is invalid. Previously, an E_WARNING was raised and false was returned.
8.0.0characters is nullable now.

See also

explode(), preg_split(), count_chars(), substr_count()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page str_word_count() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.