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:
Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.
str_word_count(string, return, char)
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.
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.
- How to replace all words with another words in HTML ?
- How to calculate the number of words in a string using JQuery?
- How to find sub-string between the two words using jQuery ?
- How to make horizontal line with words in the middle using CSS?
- How to make sure clients have enough words in textarea by using angularjs in order to disable/enable a button?
- Lodash _.words() Method
- Python program to crawl a web page and get most frequent words
- PHP | Program to check a string is a rotation of another string
- PHP Program to Count number of binary strings without consecutive 1's
- PHP Program to Count trailing zeroes in factorial of a number
- PHP | Find the number of sub-string occurrences
- How to convert a string into number in PHP?
- How to find number of characters in a string in PHP ?
- PHP | Check if a number is Perfect number
- PHP | Check if a number is armstrong number
- PHP Program to Find the Number Occurring Odd Number of Times
- PHP 5 vs PHP 7
- PHP | Get PHP configuration information using phpinfo()
- PHP | php.ini File Configuration
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.