How to Count Number of Words in a String in PHP

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.

Output

3

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.

Output

3

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.

Output

2

The above example shows that there are 2 words present in the given string.

You May Also Like to Read

Join the Conversation

1 Comment

  1. 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

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.