How to Count Words in a String in PHP Easily
To count words in a string in PHP, use the
str_word_count() function which returns the number of words found. You simply pass your string as an argument like str_word_count($string) to get the word count.Syntax
The str_word_count() function counts the number of words in a string.
str_word_count(string $string, int $format = 0, string $charlist = '')- $string: The input string 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
int str_word_count(string $string, int $format = 0, string $charlist = '')
Example
This example shows how to count words in a string using str_word_count(). It prints the total number of words found.
php
<?php $text = "Hello world! Welcome to PHP programming."; $wordCount = str_word_count($text); echo "Number of words: " . $wordCount; ?>
Output
Number of words: 6
Common Pitfalls
One common mistake is expecting str_word_count() to count punctuation or numbers as words. It only counts alphabetic words by default. Also, special characters like apostrophes or hyphens may not be counted as part of words unless specified in $charlist.
For example, contractions like "don't" may be counted as two words unless you add the apostrophe to $charlist.
php
<?php // Wrong: counts 'don' and 't' as separate words $text = "I don't know."; echo str_word_count($text); // Outputs 3 // Right: include apostrophe to count as one word echo str_word_count($text, 0, "'"); // Outputs 2 but treats don't as one word ?>
Output
3
2
Quick Reference
Here is a quick summary of str_word_count() usage:
| Parameter | Description | Default |
|---|---|---|
| $string | The input string to count words from | Required |
| $format | 0 = count words (int), 1 = return array of words, 2 = return array with positions | 0 |
| $charlist | Additional characters to consider part of words (e.g., apostrophes) | Empty string |
Key Takeaways
Use str_word_count() to count words in a PHP string easily.
By default, it counts alphabetic words and ignores punctuation.
Add characters like apostrophes in $charlist to count contractions correctly.
Use the $format parameter to get word arrays or positions if needed.
Test your input strings to handle special cases like hyphens or numbers.