I am looking for the shortest, simplest and most elegant way to count the number of capital letters in a given string.
The strtoupper() function converts a string to uppercase. Note: This function is binary-safe. Related functions: strtolower() - converts a string to lowercase.
The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.
function count_capitals($s) { return mb_strlen(preg_replace('![^A-Z]+!', '', $s)); }
$str = "AbCdE";
preg_match_all("/[A-Z]/", $str); // 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With