-
-
Notifications
You must be signed in to change notification settings - Fork 578
Expand file tree
/
Copy pathCountVowels.php
More file actions
57 lines (47 loc) · 1.53 KB
/
Copy pathCountVowels.php
File metadata and controls
57 lines (47 loc) · 1.53 KB
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
50
51
52
53
54
55
56
57
<?php
declare(strict_types=1);
/**
* 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.
*
* @return int $numberOfVowels
* @throws \Exception
*/
function countVowelsSimple(string $string): int
{
// Check for an empty string and throw an exception if so.
if ($string === '' || $string === '0') {
throw new \Exception('Please pass a non-empty string value.');
}
// Initialize variables.
$numberOfVowels = 0;
$vowels = ['a', 'e', 'i', 'o', 'u']; // Set of vowels for comparison.
// Convert the string to lowercase for case-insensitive comparison.
$string = strtolower($string);
// Split the string into an array of characters.
$characters = str_split($string);
// Loop through each character to count the vowels.
foreach ($characters as $character) {
if (in_array($character, $vowels)) {
$numberOfVowels++;
}
}
// Return the total number of vowels found.
return $numberOfVowels;
}
/**
* This function returns the Total number of vowels present in the given
* string using a regular expression.
*
* @return int
* @throws \Exception
*/
function countVowelsRegex(string $string): int|false
{
if ($string === '' || $string === '0') {
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);
}