How to Count the Number of Words in a String using PHP

You can count the number of words in a given string using the PHP string function str_word_count(). See the below code:


$str = "Find number of words in this sentence";
$count = str_word_count($str);

Using this PHP string function, you can display the number of words in a sentence in a PHP program. See the below code that displays the number of words in a string:


<html>
<head>
	<title>
		Count number of words using PHP
	</title>
</head>
<body style="text-align: center;">
	<h1 >PHP program to count number of words in a Sentence</h1>
	<?php 
	$str = "Find number of words in this sentence";
	$count = str_word_count($str);
	echo "<h2>Number of words in the sentence - \"$str\" is = <span style='color:blue;'>".$count."<span></h2>";
	?>
</body>
</html>

We are using a PHP variable $str to hold the input string, the number of words of which we want to count. In the next line, str_word_count($str) function counts the number of words. Let us name this file as index.php and save it in a folder "word_count" under htdocs.

word count in phpTest the Application

Run localhost/word_count in the browser. You will see the page opened with the count displayed in blue color.

Word Count in PHP

Now, let us change the above code a little bit. See below:


<html>
<head>
	<title>
		Count number of words using PHP
	</title>
</head>
<body style="text-align: center;">
	<h1 >PHP program to count number of words in a Sentence</h1>
	<?php 
	$str = "Find number of words in this sentence";
	$arr = str_word_count($str,1);
	for ($i = 0;$i<count($arr);$i++)
		echo $arr[$i].' ';

		echo "<br>";
		echo "No. of words = ".$i;
	
	?>
</body>
</html>

This time while calling the function str_word_count(), we used a format "1" as another parameter. The default is "0" which counts the number of words. But, if we specify the format as "1", it returns an array with all the words in the sentence. So, using a FOR loop we are displaying the words from the array. Now, if you save it as word_count.php and run it in the browser, it will display the input string itself and the count of words in the string. See the below output:

Word Count in PHP

word codunt in phpNote

You can also use the format "2" in the function. In that case, it will return an associative array. Use the index and corresponding word as the values to display from the associative array.

Post a Comment

Save my Name and Email id for future comments