PHP Count the total number of words in a string

Including the words in a string: Here, we will figure out how to check the complete number of words in a string in PHP?

Given a string and we need to tally the complete number of words in it.

str_word_count() function

To locate the all outnumber of words in a string, we can utilize str_word_count() function – which is a library function in PHP – it restores the complete number of words in the string.

Syntax:

str_word_count(string,return,char); 

Here,

  • the string is a necessary parameter, this is the string where we need to locate the complete number of words.
  • return – it is a discretionary parameter utilized for indicating the arrival type – it can acknowledge three values
  • 0 – Which is the default value, it determines the arrival the number of words in the string.
  • 1 – It determines the arrival of the exhibit with the words.
  • 2 – It determines the arrival of the exhibit where the key is the position and value is the real word.

roast – it is a discretionary parameter – it is utilized to determine an extraordinary character to consider as a word.

PHP code to check the complete number of words in a string

<?php
//input string
$str = "The Quick brown fox jumps right over The Lazy Dog";
//counting the words by calling str_word_count function
$response = str_word_count($str);
//printing the result
echo "There are ".$response." Words in <b>".$str."</b>".'<br/>';

//input string
$str = "Hello @ 123 . com";
//counting the words by calling str_word_count function
$response = str_word_count($str);
//printing the result
echo "There are ".$response." Words in <b>".$str."</b>".'<br/>';

//input string
$str = "Hello @ JustTechReview @ com";
//counting the words by calling str_word_count function
//specify the '@' as a word
$response = str_word_count($str, 0, '@');
//printing the result
echo "There are ".$response." Words in <b>".$str."</b>".'<br/>';
?>

Output

There are 10 Words in The Quick brown fox jumps right over The Lazy Dog
There are 2 Words in Hello @ 123 . com
There are 5 Words in Hello @ JustTechReview @ com

Clarification:

In PHP, We have the function str_word_count() to include the number of words in a string. We utilize the equivalent to get the number of words in the string ($str) and store the output of the function in ($response) at that point use reverberation to print the outcome.

Leave a Comment

error: Alert: Content is protected!!