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:

str_word_count(string, return_format, charlist);
  • 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

<?php $string = "Hello world!"; $word_count = str_word_count($string); echo "Number of words: " . $word_count; ?>

Output:

Number of words: 2

Explanation: The string "Hello world!" contains two words: "Hello" and "world", so the output is 2.

Example 2: Returning an Array of Words

<?php $string = "PHP is awesome!"; $words = str_word_count($string, 1); print_r($words); ?>

Output:

Array ( [0] => PHP [1] => is [2] => awesome )

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

<?php $string = "Hello world, PHP!"; $words_with_positions = str_word_count($string, 2); print_r($words_with_positions); ?>

Output:

Array ( [0] => Hello [6] => world [13] => PHP )

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 position 0
  • "world" starts at position 6
  • "PHP" starts at position 13

Example 4: Using Additional Characters with charlist

<?php $string = "It's a user's guide!"; $words = str_word_count($string, 1, "'"); // Apostrophe considered part of the words print_r($words); ?>

Output:

Array ( [0] => It's [1] => a [2] => user's [3] => guide )

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.