PHP Function str_word_count() – Return information about words used in a string

The str_word_count() function is used to count the number of words in a string. This function was introduced in PHP4. The value of format dictates the returned value:

value returned value
0 (default) The number of words found in string
1 An array of all words found in string
2 An associative array, with keys being the positions and values being the words found at those positions in string

Syntax:

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

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.

Parameters

Parameter Description
string The string
format Specify the return value of this function. (0 or 1 or 2)
characters A list of additional characters which will be considered as ‘word’

Return Values

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

Examples

Example 1:

<?php
$text = “Good morning friends! have nice day”; $a=str_word_count($text,1); $b=str_word_count($text,2); $c=str_word_count($text);
print_r($a);
print_r($b);
print $c;
?>

The output of the above program is as follows:

Array
(
[0] => Good
[1] => morning
[2] => friends
[3] => have
[4] => nice 
[5] => day )
Array
(
[0] => Good 
[5] => morning 
[13] => friends 
[22] => have 
[27] => nice 
[32] => day
)
6
Related Post