$str="Welcome to Plus2net.com to learn PHP";
echo str_word_count($str); // Output is 8
Syntax
str_word_count ( $input_string, int $format, $char_list)
Parameter | DESCRIPTION |
---|---|
$input_string | Required : Input string |
$format | Optional : 0 : Output gives number of words found. ( default ) 1 : Output gives an array with all the words present in Input string 2 : Output gives an associative array with key giving position of the word inside the string with value holding the Word. |
$char_list | Optional : Additional chars to be considered as Word. |
$str="Welcome to Plus2net.com to learn PHP";
$ar=str_word_count($str,1); // Output is an array.
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
0 -> Welcome
1 -> to
2 -> Plus
3 -> net
4 -> com
5 -> to
6 -> learn
7 -> PHP
By using $format=2 we will get associative array showing key as position of the words.
$str="Welcome to Plus2net.com to learn PHP";
$ar=str_word_count($str,2); // Output is an array.
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
0 -> Welcome
8 -> to
11 -> Plus
16 -> net
20 -> com
24 -> to
27 -> learn
33 -> PHP
By adding optional parameter $char_list, we will add additional chars to consider as Word
$str="Welcome to Plus2net.com to learn PHP";
$ar=str_word_count($str,1,'2');
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
0 -> Welcome
1 -> to
2 -> Plus2net
3 -> com
4 -> to
5 -> learn
6 -> PHP
Now let us add . and 2 to char list to consider as Word
$str="Welcome to Plus2net.com to learn PHP";
$ar=str_word_count($str,1,'2,.');
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
0 -> Welcome
1 -> to
2 -> Plus2net.com
3 -> to
4 -> learn
5 -> PHP
With associative array to show position of the words inside the string
$str="Welcome to Plus2net.com to learn PHP";
$ar=str_word_count($str,2,'2,.');
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
0 -> Welcome
8 -> to
11 -> Plus2net.com
24 -> to
27 -> learn
33 -> PHP
By using above code to list out words present in a string, we can count the frequency of occurrence of each word by using array_count_values()
$str="Welcome to Plus2net.com to learn PHP";
$ar=array_count_values(str_word_count($str,1,'2,.'));
while (list ($key, $val) = each ($ar)) {
echo "$key -> $val <br> ";
}
Output is here
Welcome -> 1
to -> 2
Plus2net.com -> 1
learn -> 1
PHP -> 1