PHP Tutorial - PHP str_word_count() Function






Definition

The str_word_count() function returns the number of words in a string.

Syntax

PHP str_word_count() Function has the following syntax.

mixed str_word_count ( string str [, int count_type [, string char_list]] )

Parameter

ParameterDescription
stringThe string
formatSpecify the return value of this function.
charlistA list of additional characters which will be considered as 'word'

Format

The current supported values for format 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




Return

PHP str_word_count() Function returns an array or an integer, depending on the format chosen.

Example

Here are examples of the three options:


<?PHP// ww w .  j  av  a  2 s. com
$str = "This is a test from java2s.com."; 
$a = str_word_count($str, 1); 
print_r($a); 
print "\n"; 
$b = str_word_count($str, 2); 
print_r($b);
print "\n";  
$c = str_word_count($str); 
print_r($c); 

echo "There are $c words in the string\n";
?>

The code above generates the following result.