forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountVowels.php
49 lines (44 loc) · 1.22 KB
/
CountVowels.php
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
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
* This function returns the total number of vowels present in
* the given string using a simple method of looping through
* all the characters present in the string.
*
* @param string $string
* @return int $numberOfVowels
*/
function countVowelsSimple(string $string)
{
if (empty($string))
{
throw new \Exception('Please pass a non-empty string value');
}
$numberOfVowels = 0;
$vowels = ['a', 'e', 'i', 'o', 'u']; // Vowels Set
$string = strtolower($string); // For case-insensitive checking
$characters = str_split($string); // Splitting the string to a Character Array.
foreach ($characters as $character)
{
if (in_array($character, $vowels))
{
$numberOfVowels++;
}
}
return $numberOfVowels;
}
/**
* This function returns the Total number of vowels present in the given
* string using a regular expression.
*
* @param string $string
* @return int
*/
function countVowelsRegex(string $string)
{
if (empty($string))
{
throw new \Exception('Please pass a non-empty string value');
}
$string = strtolower($string); // For case-insensitive checking
return preg_match_all('/[a,e,i,o,u]/', $string);
}