What is the str_word_count method in PHP?
Overview
In PHP, the str_word_count() method counts the number of words in a string and returns the count value. It has been a part of the standard library in PHP, which has been available since PHP version 4.3 and later.
Syntax
str_word_count($string,$format, $characters)
Parameters
$string: The string whose words are counted.$format: This is an integer value that indicates the function’s return value. The supported values are listed below:0returns the number of words found.1is an array that has all the strings found in$string.2returns an associative array. The array key is the numeric position of the word inside the$string, and the array value is the actual word itself.
Note: The
$formatparameter only supports0,1, and2as valid values.
$character: This parameter indicates the list of other characters to be seen as words.
This function only identifies a group of letters as a word. If a number or any other character is part of the input
$string, it is considered a word on its own. In that case, it is only returned as a part of the counted word if passed as a character parameter.
Example
<?php// a normal string$str = "It is surely a bright day today";//string with some space$strings = "It is surely a bright day today";// strings with number and special character$stringing = "Hello wor3ld enjoy y%our day";// the format param defaults to zeroprint_r(str_word_count($str));echo "\n";//this will print a simple index arrayprint_r(str_word_count($str,1));// an associative array is displayed.print_r(str_word_count($str,2));// This count shows that spaces are not countedecho "\n" ;print_r(str_word_count($strings));echo "\n";/* with the character param thespecial char is returned*/print_r(str_word_count($stringing, 1,'3%'));echo "\n";print_r(str_word_count($stringing));?>
Explanation
-
Line 5–11: We define three string variables
$str,$string, and$stringing. -
Line 14: We count the
$strstring and print the count result. -
Line 18: We call the
str_word_count()function on the string with the$formatparameter passed as1. It returns an indexed array. -
Line 25–31: We count the words in the
$stringsand$stringingstring variables. -
Line 21: We call the
str_word_count()function on$stringingwith the$formatparameter set as1. It returns an indexed array. We set the$characterparameter as3%. This causes the function to consider3and%found in the$stringingvariable as separate words.