How to Use str_word_count in PHP: Syntax and Examples
Use
str_word_count in PHP to count the number of words in a string or to return an array of words. It accepts the string to analyze and an optional format parameter to control the output type.Syntax
The str_word_count function has this syntax:
str_word_count(string $string, int $format = 0, string $charlist = '')
string: The text to count words from.
format: Optional. 0 returns the number of words (default), 1 returns an array of words, 2 returns an associative array with word positions.
charlist: Optional. Additional characters to consider as part of a word.
php
str_word_count(string $string, int $format = 0, string $charlist = ''): int|array
Example
This example shows how to count words and get an array of words from a string using str_word_count.
php
<?php $text = "Hello world! Let's count words."; // Count words $wordCount = str_word_count($text); echo "Word count: $wordCount\n"; // Get array of words $wordsArray = str_word_count($text, 1); print_r($wordsArray); // Get associative array with word positions $wordsAssoc = str_word_count($text, 2); print_r($wordsAssoc); ?>
Output
Word count: 6
Array
(
[0] => Hello
[1] => world
[2] => Let
[3] => s
[4] => count
[5] => words
)
Array
(
[0] => Hello
[6] => world
[12] => Let
[15] => s
[17] => count
[23] => words
)
Common Pitfalls
One common mistake is expecting str_word_count to handle apostrophes or special characters as part of words by default. For example, contractions like "Let's" are split into two words "Let" and "s". To fix this, use the charlist parameter to include apostrophes.
Also, remember that punctuation marks are not counted as words.
php
<?php $text = "Let's test this."; // Without charlist - splits "Let's" into two words $wordsDefault = str_word_count($text, 1); print_r($wordsDefault); // With charlist to include apostrophe $wordsWithApostrophe = str_word_count($text, 1, "'"); print_r($wordsWithApostrophe); ?>
Output
Array
(
[0] => Let
[1] => s
[2] => test
[3] => this
)
Array
(
[0] => Let's
[1] => test
[2] => this
)
Quick Reference
Summary of str_word_count usage:
- format = 0: Returns the number of words (integer).
- format = 1: Returns an indexed array of words.
- format = 2: Returns an associative array with word positions as keys.
- charlist: Add characters like apostrophes to treat them as part of words.
Key Takeaways
Use str_word_count to count words or get words as arrays from a string.
The format parameter controls output: 0 for count, 1 for word list, 2 for word positions.
Use the charlist parameter to include special characters like apostrophes in words.
Without charlist, contractions may split into separate words.
Punctuation is not counted as words by default.