Count the number of words in the string "Hello World!":
<?phpecho str_word_count("Hello world!");?>The str_word_count() function counts the number of words in a string.
str_word_count( string,return,char )
parameter | describe |
---|---|
string | Required. Specifies the string to check. |
return | Optional. Specifies the return value of the str_word_count() function. Possible values: 0 - Default. Returns the number of words found. 1 - Returns an array containing the words in the string. 2 - Returns an array where the keys are the word positions in the string and the keys are the actual words. |
char | Optional. Specifies special characters that are recognized as words. |
Return value: | Returns a number or an array, depending on the return parameter selected. |
---|---|
PHP version: | 4.3.0+ |
Update log: | In PHP 5.1, the char parameter was added. |
Return an array containing the words in a string:
<?phpprint_r(str_word_count("Hello world!",1));?>Returns an array where the key is the word's position in the string and the key value is the actual word:
<?phpprint_r(str_word_count("Hello world!",2));?>Without char parameters and with char parameters:
<?phpprint_r(str_word_count("Hello world & good morning!",1));print_r(str_word_count("Hello world & good morning!",1,"&"));?>