PHP str_word_count() function
Example
Calculate the number of words in the string "I love Shanghai!":
<?php echo str_word_count("I love Shanghai!"); ?>
Definition and Usage
The str_word_count() function calculates the number of words in a string.
Syntax
str_word_count(string,return,char)
Parameters | Description |
---|---|
string | Required. Specifies the string to be checked. |
return |
Optional. Specifies the return value of the str_word_count() function. Possible Values:
|
char | Optional. Specifies the special characters that are considered as words. |
Technical Details
Return Value: | Returns a number or an array depending on the selected return Parameters. |
PHP Version: | 4.3.0+ |
Update Log: | In PHP 5.1, a new feature was added: char Parameters. |
More Examples
Example 1
Returns an array containing the words in the string:
<?php print_r(str_word_count("I love Shanghai!",1)); ?>
Example 2
Returns an array with the key names being the position of the words in the string and the key values being the actual words:
<?php print_r(str_word_count("I love Shanghai!",2)); ?>
Example 3
Setting and not setting the char parameter:
<?php print_r(str_word_count("I love Shanghai & good morning!",1)); print_r(str_word_count("I love Shanghai & good morning!",1,"&")); ?>