Last Updated on May 12, 2021 by Roshan Parihar
In this tutorial, learn how to count number of words in a string using PHP. The short answer is: use the str_word_count()
and pass string variable as an argument.
However, there are many other methods to get the number of words present in a string using PHP. Let’s find out with the examples given below.
Method 1: Count Number of Words in a String Using str_word_count() in PHP
You can use the str_word_count()
function of PHP to count the number of words in a string. It takes the string variable as an argument to get the number of words present in it. let’s see the example to learn the method.
1 2 3 4 5 6 7 |
<?php // String variable $myStr = "Welcome to TutorialDeep!"; //Count number of words in a string echo str_word_count($myStr); // output: 3 ?> |
Output
The above example first declares the string. After that, it counts that there are 3 words present in the specified string.
Method 2: Using preg_replace(), trim(), explode, and count() in PHP
You can create a function that counts the number of words in a string in PHP. The function first uses the trim()
and preg_replace()
to return the array of string by matching the patterns. furthermore, it uses the explode()
function to convert it into an array. After that, it returns the number of words in a string using the count()
in PHP.
It requires to call the function and pass the string variable as its argument to find the words present in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php //function that counts the number of words in a string function get_str_num_words($string){ $string = preg_replace('/\s+/', ' ', trim($string)); $words = explode(" ", $string); return count($words); } //String variable $$mystr = "Welcome to TutorialDeep!"; //Call function to get number of words $mylen = get_str_num_words($mystr); //Print number of words in the given string echo $mylen; ?> |
Output
The above example is lengthy to use. However, it finds the correct number of words in a string. The output shows that there are 3 words present in the given string variable.
Method 3: Using explode() and sizeof() in PHP
In addition to the above all methods, you can also find the words in a string only the explode()
and sizeof()
of PHP. The explode()
function first breaks the string into an array. After that, it find the size of the array using the sizeof()
that gives the number of words in a string.
1 2 3 4 5 6 7 8 9 10 |
<?php //Define string variable $myStr = "Hello World!"; //Break string into array $mystrarr = explode(" ",$myStr); //Get size of string by counting array elements echo sizeof($mystrarr); ?> |
Output
The above example shows that there are 2 words present in the given string.
You May Also Like to Read
How can I extract the number of 2 sequence words?
For example:
Text: “I would like to have the amount of 2 words of this sentence”
Results: “I would” + “would like” + “like to” + “to have” + “have the” + “the amount” + “amount of” and so on