PHP str_word_count() function
The str_word_count()
function in PHP is used to count the number of words in a string. A word is defined as a sequence of alphanumeric characters, and this function allows you to count words, return an array of words, or return the positions of the words in the string.
Syntax:
- string: The input string in which you want to count words.
- return_format: Optional. Specifies the return type.
0
(default) – returns the number of words.1
– returns an array containing all words found in the string.2
– returns an associative array, where the keys are the positions of words in the string, and the values are the words themselves.
- charlist: Optional. A list of additional characters considered as part of a word (e.g., apostrophes or hyphens).
Example 1: Counting the Number of Words
Output:
Explanation: The string "Hello world!"
contains two words: "Hello"
and "world"
, so the output is 2
.
Example 2: Returning an Array of Words
Output:
Explanation: When the second argument is 1
, str_word_count()
returns an array of words. Here, it splits the string "PHP is awesome!"
into the words "PHP"
, "is"
, and "awesome"
.
Example 3: Returning Words with Their Positions
Output:
Explanation: When the second argument is 2
, str_word_count()
returns an associative array where the keys are the starting positions of each word in the string. In this case:
"Hello"
starts at position0
"world"
starts at position6
"PHP"
starts at position13
Example 4: Using Additional Characters with charlist
Output:
Explanation: The third argument (charlist
) allows you to include specific characters in words. Here, the apostrophe ('
) is included, so words like "It's"
and "user's"
are treated as single words, rather than being split.
Key Points:
str_word_count()
treats a "word" as a sequence of alphanumeric characters.- By default, it only counts words, but you can also return an array of words or an array of words with their positions.
- The
charlist
parameter allows you to customize which characters are treated as part of a word.
This function is useful for tasks such as word counting, text parsing, and text manipulation in PHP.