Home »
PHP »
PHP programs
PHP | Count the total number of words in a string
Given a string. Learn, how to count total words in it?
Submitted by Bhanu Sharma, on August 10, 2019 [Last updated : March 13, 2023]
PHP - Counting String Words
Given a string and we have to count the total number of words in it.
str_word_count() function
To find the total number of words in a string, we can use str_word_count() function – which is a library function in PHP – it returns the total number of words in the string.
Syntax
str_word_count(string,return,char);
Here,
- string is a required parameter, this is the string in which we have to find the total number of words.
-
return – it is an optional parameter used for specifying the return type – it can accept three values
- 0 – Which is the default value, it specifies the return the number of words in the string.
- 1 – It specifies the return of the array with the words.
- 2 – It specifies the return of the array where key is the position and value is the actual word.
- char – it is an optional parameter – it is used to specify a special character to consider as a word.
PHP code to count the total 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 @ IncludeHelp @ 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 @ IncludeHelp @ com
Explanation
In PHP, We have the function str_word_count() to count the number of words in a string. We use the same to get the number of words in the string ($str) and store the output of the function in ($response) then use echo to print the result.
PHP String Programs »