PHP str_word_count()Functions
Examples
Count the number of words in the string "Hello World!":
<?php
echo str_word_count("Hello world!");
?>
echo str_word_count("Hello world!");
?>
Run Example »
Definition and Usage
The str_word_count() function counts the number of words in a string.
Syntax
str_word_count(string,return,char)
| Parameters | Description |
|---|---|
| string | Required. Specifies the string to check. |
| return | Optional. Specifies the return value of the str_word_count() function. Possible values:
|
| char | Optional. Specifies special characters to be treated as words. |
Technical Details
| Return Value: | Returns a number or an array, depending on the chosenreturnparameters. |
|---|---|
| PHP Version: | 4.3.0+ |
| Changelog: | In PHP 5.1, thecharparameter was added. |
More Examples
Example 1
Returns an array containing the words in the string:
<?php
print_r(str_word_count("Hello world!",1));
?>
print_r(str_word_count("Hello world!",1));
?>
Run Example »
Example 2
Returns an array where the keys are the positions of the words in the string, and the values are the actual words:
<?php
print_r(str_word_count("Hello world!",2));
?>
print_r(str_word_count("Hello world!",2));
?>
Run Example »
Example 3
Without the char parameter and with the char parameter:
<?php
print_r(str_word_count("Hello world & good morning!",1));
print_r(str_word_count("Hello world & good morning!",1,"&"));
?>
print_r(str_word_count("Hello world & good morning!",1));
print_r(str_word_count("Hello world & good morning!",1,"&"));
?>
Run Example »
PHP String Reference Manual Other Extensions