PHP str word count

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP : str_word_count() function

Description

The str_word_count() function is used to count the number of words in a string.

Version

(PHP 4 and above)

Syntax

str_word_count(string_name, nformat, add_chars)

Parameter

Name

Description

Required /
Optional

Type

string_name

The input string.

Required

String

nformat

Specifies the return value of the str_word_count() function. 
Supported values :
0 - returns the number of words found. 
1 - returns an array contains all the words found within the specified 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.

Optional

Integer

add_chars

A list of additional characters which will be considered as 'word'.

Optional

String

Return value

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

Value Type : Mixed.

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Pictorial Presentation

php-string-str_word_count()

Example :

  1. $string_name='Welcome to w3resource.com';  

  2. print_r(str_word_count($string_name,0));  

  3. echo '
    ';  

  4. print_r(str_word_count($string_name,1));  

  5. echo '
    ';  

  6. print_r(str_word_count($string_name,2));  

  7. ?>  

Output :

5
Array ( [0] => Welcome [1] => to [2] => w [3] => resource [4] => com ) 
Array ( [0] => Welcome [8] => to [11] => w [13] => resource [22] => com )