![]() |
VOOZH | about |
Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:
Table of Content
The str_word_count() method counts the number of words in a string.
Syntax:
str_word_count(string, return, char)
Example:
3
A flexible approach that first cleans the string, then counts words manually.
Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method.
Step 2: Convert the string into an array using the explode() method.
Step 3: Now count() method counts the number of elements in an array.
Step 4: Resultant is the number of words in a string.
Example:
3
A lightweight method that counts spaces after normalizing the string.
Step 1: Remove the trailing and leading white spaces using the trim() method.
Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method.
Step 3: Now counts the number of word in a string using substr_count($str, " ")+1 and return the result.
Example:
3
You can count the number of words in a string using strtok() in PHP. Tokenize the string using spaces as delimiters, incrementing a counter for each token until no more tokens are left, effectively counting the words.
Example: In this example use strtok() to tokenize the string by spaces and count each token, effectively counting the number of words in the string. The output of the provided example string " Geeks for Geeks " will be 3.
3
Using `preg_match_all()` in PHP with the pattern `/(\w+)/u` efficiently counts words by matching sequences of word characters (`\w+`). It returns the number of matches found in the string, providing a robust solution for word counting tasks.
Example
2
Another approach to count the number of words in a string in PHP involves using explode() along with array_filter() function. This method splits the string into an array of words based on spaces, filters out empty elements, and counts the remaining elements.
Example:
2