Using PHP str_word_count() Function to Count Words in a String
This article explains the PHP str_word_count() function, its syntax, parameters, and provides multiple code examples showing how to count words, retrieve word arrays, obtain word positions, customize ignored characters, and use regular expressions for word matching.
In PHP, the str_word_count() function counts the number of words in a string. This article explains its syntax, parameters, and provides multiple code examples demonstrating different usage scenarios.
Function Syntax
<code>str_word_count(string $string [, int $format = 0 [, string $charlist]])</code>Parameter Description
$string : required, the string to be examined.
$format : optional, determines the return format (0, 1, or 2). Default is 0, which returns the word count.
$charlist : optional, a list of characters to ignore when counting words; defaults to whitespace characters.
Usage Examples
Example 1: Count words in a string
<code>$string = "Hello, how are you today?";
$wordCount = str_word_count($string);
echo "Word count: " . $wordCount;
</code>Output: Word count: 5
Example 2: Return each word as an array
<code>$string = "Hello, how are you today?";
$wordsArray = str_word_count($string, 1);
echo "Word list: ";
foreach ($wordsArray as $word) {
echo $word . " ";
}
</code>Output: Word list: Hello how are you today
Example 3: Return positions and words
<code>$string = "Hello, how are you today?";
$wordsArray = str_word_count($string, 2);
echo "Word list: ";
foreach ($wordsArray as $position => $word) {
echo "Pos" . $position . ":" . $word . " ";
}
</code>Output: Word list: Pos0:Hello Pos6:how Pos10:are Pos14:you Pos18:today
Example 4: Custom ignore character list
<code>$string = "Hello, how are you today?";
$wordCount = str_word_count($string, 0, "o");
echo "Word count: " . $wordCount;
</code>Output: Word count: 3
Example 5: Using regular expression to match words
<code>$string = "Hello, how are you today?";
preg_match_all('/\w+/', $string, $matches);
echo "Word list: ";
foreach ($matches[0] as $word) {
echo $word . " ";
}
</code>Output: Word list: Hello how are you today
The str_word_count() function is a simple yet powerful tool for string processing in PHP, allowing developers to obtain word counts, lists, positions, and customize ignored characters, making it valuable for various text analysis 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.