I am looking for the shortest, simplest and most elegant way to count the number of capital letters in a given string.
-
6If you'd like to cheat: strlen(strtoupper($str)) ;) – Steven Mercatante Oct 13 '09 at 02:47
-
Simplest and most elegant != code golf – Sam Harwell Oct 13 '09 at 02:52
-
4str_replace(range('A', 'Z'), '', $str, $num_caps); echo $num_caps; – GZipp Oct 13 '09 at 05:00
5 Answers
function count_capitals($s) {
return mb_strlen(preg_replace('![^A-Z]+!', '', $s));
}
-
-
@emix the regex to support all the special characters (diacritics) is `/[^\p{Lu}]/u` – Almino Melo Mar 03 '20 at 22:53
-
1@emix, @Almino Melo, and use mb_strlen for multibyte strings when using `/[^\p{Lu}]/u` – Beta Projects Apr 26 '21 at 21:41
George Garchagudashvili Solution is amazing, but it fails if the lower case letters contain diacritics or accents.
So I did a small fix to improve his version, that works also with lower case accentuated letters:
public static function countCapitalLetters($string){
$lowerCase = mb_strtolower($string);
return strlen($lowerCase) - similar_text($string, $lowerCase);
}
You can find this method and lots of other string common operations at the turbocommons library:
EDIT 2019
The method to count capital letters in turbocommons has evolved to a method that can count upper case and lower case characters on any string. You can check it here:
Read more info here:
And it can also be tested online here:
https://turbocommons.org/en/app/stringutils/count-capital-letters

- 706
- 1
- 6
- 20
I'd give another solution, maybe not elegant, but helpful:
$mixed_case = "HelLo wOrlD";
$lower_case = strtolower($mixed_case);
$similar = similar_text($mixed_case, $lower_case);
echo strlen($mixed_case) - $similar; // 4

- 7,443
- 12
- 45
- 59
-
3Seems like this solution would work even for capital letters with diacritics on them. +1 – LittleTiger Oct 24 '16 at 04:33
It's not the shortest, but it is arguably the simplest as a regex doesn't have to be executed. Normally I'd say this should be faster as the logic and checks are simple, but PHP always surprises me with how fast and slow some things are when compared to others.
function capital_letters($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
echo 'caps: ' . capital_letters('HelLo2') . "\n";

- 657
- 5
- 11
-
3Function *count\_capitals* is faster by far. With very short strings *count\_capitals* is only a little faster but with the first paragraph of "Lorem ipsum..." it's 0.03 seconds to run 3000 iterations vs. 1.8 seconds to run the same string through function *capital\_letters* 3000 times. – Nov 02 '10 at 02:03