Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to count the vowels in a string in PHP?

Tags:

php

If I define a simple string variable, how would I count and output the number of vowels in the string in the simplest possible way?

I have searched and found a number of similar ways to do so, but most seem more complex than necessary. They are all functional and maybe the complexity IS necessary, but I am looking for the simplest solution possible.

My string variable would be something like:

$someString = "This is some text with some more text and even more text."

I just want to display the total instances of a,e,i,o,u. Thank you in advance.

like image 814
Jake Avatar asked Sep 19 '11 00:09

Jake


2 Answers

Here's an easy solution:

<?php
$string = "This is some text with some more text and even more text.";
echo "There are <strong>".preg_match_all('/[aeiou]/i',$string,$matches)." vowels</strong> in the string <strong>".$string."</strong>";
?>
like image 71
Nathan Avatar answered Sep 23 '22 17:09

Nathan


Why not just

$Vowels = substr_count($someString, 'a')+substr_count($someString, 'e')+substr_count($someString, 'i')+substr_count($someString, 'o')+substr_count($someString, 'u');

I would, however, encase it in a function otherwise you would have to change the names of the variables every time you want to reuse it:

function CountVowels($String) {
    return substr_count($String, 'a')+substr_count($String, 'e')+substr_count($String, 'i')+substr_count($String, 'o')+substr_count($String, 'u');
}

echo CountVowels('This is some text with some more text and even more text.');
//Echos 17

--

2018 Update:

This could be much neater as

function count_vowels(string $s): int {
  return array_sum(array_map(function ($vowel) use ($s) { 
    return substr_count($s, $vowel); 
  }, ['a', 'e', 'i', 'o', 'u']));
}

count_vowels('This is some text with some more text and even more text.');

However, as others pointed out, this may not be the fastest on long strings since it has to iterate through the string 5 times.

like image 26
Gricey Avatar answered Sep 23 '22 17:09

Gricey