In this example you are going to learn how to count the number of vowels in a string in PHP. I’m going to show you two methods of finding the vowels from a string, one is using Array and For loop and the other method is using Regex. First method is little bit bigger but will give some ideas about PHP function to the beginners.
Lets see the code (using Array and For loops):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<html> <body> <h2>Find Number of Vowels in a String - PHP Script by <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h2> <form action="" method="post"> <input type="text" name="string" /> <input type="submit" /> </form> </body> </html> <?php if($_POST) { //get the input value and convert string to lowercase $string = strtolower($_POST['string']); //all vowels in array $vowels = array('a','e','i','o','u'); //find length of the string $len = strlen($string); $num = 0; //loop through each letter for($i=0; $i<$len; $i++){ if(in_array($string[$i], $vowels)) { $num++; } } //output echo "Number of vowels : <span style='color:green; font-weight:bold;'>". $num ."</span>"; } ?> |
The second method is very simple (counting the vowels using preg_match_all()):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<html> <body> <h2>Find Number of Vowels in a String - PHP Script by <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h2> <form action="" method="post"> <input type="text" name="string" /> <input type="submit" /> </form> </body> </html> <?php if($_POST) { $string = strtolower($_POST['string']); $num = preg_match_all('/[aeiou]/i',$string,$matches); echo "Number of Vowels : ". $num; } ?> |
I hope you would have liked my post, here is the demo for testing:
/[aeiou]/i in this what is i after / that is ]/i
thank u. keep it up….
why u have used $num=0 in the secod method?
can you please help me i dnt get the correct output for counting the vowels can you sent the correct code