Master PHP’s str_word_count(): Count Words, Get Arrays, and Customize Output
This guide introduces PHP’s str_word_count() function, detailing its syntax, parameters, and multiple practical examples that show how to count words, retrieve word arrays, obtain word positions, customize ignored characters, and use regular expressions for advanced string processing.
In PHP, the str_word_count() function counts the number of words in a string. This article explains its syntax, parameters, and provides code examples.
Function Syntax
str_word_count(string $string [, int $format = 0 [, string $charlist]])Parameter Description
$string: required, the string to be analyzed. $format: optional, determines the return format (0, 1, or 2), default is 0.
When $format is 0, the function returns the word count.
When $format is 1, it returns an array of words.
When $format is 2, it returns an associative array with positions as keys. $charlist: optional, list of characters to ignore; defaults to whitespace, tabs, and newlines.
Usage Examples
Below are several examples demonstrating different usages.
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
The str_word_count() function is a simple yet powerful tool for string processing in PHP, allowing you to obtain word counts, lists, positions, and customize ignored characters.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
