Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest, shortest way to count capital letters in a string with php?

Tags:

php

count

letters

I am looking for the shortest, simplest and most elegant way to count the number of capital letters in a given string.

like image 311
pablo Avatar asked Oct 13 '09 02:10

pablo


People also ask

How can I get uppercase string in PHP?

The strtoupper() function converts a string to uppercase. Note: This function is binary-safe. Related functions: strtolower() - converts a string to lowercase.

How do you check if a string is all 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.


2 Answers

function count_capitals($s) {   return mb_strlen(preg_replace('![^A-Z]+!', '', $s)); } 
like image 70
cletus Avatar answered Sep 26 '22 06:09

cletus


$str = "AbCdE";

preg_match_all("/[A-Z]/", $str); // 3
like image 42
Stream Huang Avatar answered Sep 25 '22 06:09

Stream Huang