Inside this article we will see the concept i.e PHP Program to Count The Number of Vowels in a String. Article contains the classified information about checking vowels inside string by using PHP function, logic and regular expression. Tutorial is super easy to understand and implement it in your code as well.
If you are looking for a solution to check vowels in a string using PHP functions and regular expression then this article will help you a lot for this.
Vowels are:
a, e, i, o, u
Learn More –
- JavaScript Remove All Event Listeners From an Element
- Laravel 9 Create Multi Language Website Using Google Translator
- JavaScript Check if String Contains at Least One Number
- Remove Special Characters from a String in JavaScript
Let’s get started.
Example #1: Using Loop Concept To Count Vowels
Here,
We will use the concept of PHP for loop and in_array PHP function. Create a file index.php into your localhost directory.
Open file and write this code into it,
<?php $string = "Welcome to the learning platform of Online Web Tutor"; //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(strtolower($string[$i]), $vowels)) { $num = $num + 1; } } //output echo "There are <strong>" . $num . " vowels</strong> in the string <strong>" . $string . "</strong>";
Concept
//loop through each letter
for ($i = 0; $i < $len; $i++) {
if (in_array(strtolower($string[$i]), $vowels)) {
$num = $num + 1;
}
}
Output
There are 17 vowels in the string Welcome to the learning platform of Online Web Tutor
Example #2: Using PHP Function preg_match_all
Here,
We will use the concept of PHP function preg_match_all.
The preg_match_all()
function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.
Create a file index.php into your localhost directory.
Open file and write this code into it,
<?php $string = "Welcome to the leanring platform of Online Web Tutor"; echo "There are <strong>" . preg_match_all('/[aeiou]/i', $string, $matches) . " vowels</strong> in the string <strong>" . $string . "</strong>";
Concept
preg_match_all('/[aeiou]/i', $string, $matches)
Output
There are 17 vowels in the string Welcome to the learning platform of Online Web Tutor
We hope this article helped you to learn PHP Program to Count The Number of Vowels in a String Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.