Understanding PHP str_word_count() Function: Syntax, Parameters, and Usage Examples
This article explains the PHP str_word_count() function, covering its syntax, parameter options, and providing multiple code examples that demonstrate counting words, retrieving word arrays, obtaining word positions, customizing ignored characters, and using regular expressions for word matching.
1. Overview
In PHP, the str_word_count() function is used to count the number of words in a string. This article details its usage and provides code examples.
2. Function Syntax
str_word_count(string $string [, int $format = 0 [, string $charlist]])Parameter description:
$string: required, the string to count words.
$format: optional, return format (0, 1, or 2), default is 0.
$charlist: optional, list of characters to ignore when counting words.
If $format is 0, the function returns the word count (default).
If $format is 1, the function returns an array containing each word.
If $format is 2, the function returns an associative array where the keys are the positions of the words and the values are the words themselves.
3. Usage Examples
Below are concrete code examples that illustrate how to use the function.
Example 1: Count words in a string
$string = "Hello, how are you today?";
$wordCount = str_word_count($string);
echo "Word count: " . $wordCount;Output: Word count: 5
Example 2: Return each word as an array
$string = "Hello, how are you today?";
$wordsArray = str_word_count($string, 1);
echo "Word list: ";
foreach ($wordsArray as $word) {
echo $word . " ";
}Output: Word list: Hello how are you today
Example 3: Return positions and words
$string = "Hello, how are you today?";
$wordsArray = str_word_count($string, 2);
echo "Word list: ";
foreach ($wordsArray as $position => $word) {
echo "Position" . $position . ":" . $word . " ";
}Output: Word list: Position0:Hello Position6:how Position10:are Position14:you Position18:today
Example 4: Custom ignore character list
$string = "Hello, how are you today?";
$wordCount = str_word_count($string, 0, "o");
echo "Word count: " . $wordCount;Output: Word count: 3
Example 5: Use regular expression to match words
$string = "Hello, how are you today?";
preg_match_all('/\w+/', $string, $matches);
echo "Word list: ";
foreach ($matches[0] as $word) {
echo $word . " ";
}Output: Word list: Hello how are you today
4. Conclusion
The str_word_count() function is a simple yet powerful tool for counting words, retrieving word lists, and obtaining word positions in PHP strings. By adjusting its parameters, developers can tailor its behavior for a wide range of string‑processing tasks.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.