Understanding PHP str_word_count() Function: Syntax, Parameters, and Usage Examples
This article explains PHP's str_word_count() function, detailing its syntax, parameters, and providing multiple code examples that demonstrate counting words, retrieving word arrays, obtaining word positions, customizing ignored characters, and using regular expressions for word extraction.
1. Overview
In PHP, the str_word_count() function is used to count the number of words in a string. This article introduces the function’s usage and provides corresponding code examples.
2. Function Syntax
str_word_count(string $string [, int $format = 0 [, string $charlist]])Parameter Description:
$string : The required string whose words are to be counted.
$format : Optional, determines the return format. Values can be 0, 1, or 2 (default 0). 0 – returns the word count. 1 – returns an array of words. 2 – returns an associative array where keys are the positions of the words and values are the words themselves.
$charlist : Optional, a list of characters to ignore when counting words. The default ignores spaces, tabs, and line breaks.
3. Usage Examples
Example 1: Count the number of 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 each word’s position and the word
$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: Customize ignored characters
$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. Summary
The str_word_count() function is a simple yet powerful PHP utility for processing strings. By adjusting its parameters, developers can obtain the total word count, an array of words, or an associative array with word positions, and can also define custom characters to ignore, making it widely applicable in text‑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.