PHP Programs

TheFestFever.com

Our aim is to connect students from campuses all over Delhi by making them aware of all Technical, Cultural, Management fests, workshops, Seminars organized by every college in Delhi.

Join Us Now

Program 46: Write a program to count the total number of words in a string.

total_words.php

<!DOCTYPE html>  
<html>  
<head>	
	<title>PHP Programs TutorialDuniya.com</title>
</head>
<body>
	<?php
		$sent = " If a string starts with a space, then we must not count the first space as it is not preceded by a word.  ";  
		$Count = 0;  
	
		for($i = 0; $i < strlen($sent)-1; $i++) 
		{
			if($sent[$i] == ' ' && ctype_alpha($sent[$i+1]) && ($i > 0)) 
			{  
				$Count++;  
			}  
		}  

		$Count++;  

		echo "Original string is  : ". $sent;

		echo "Total number of words in the given string: " . $Count;  
	?>  
</body>  
</html>


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.