[ACCEPTED]-simplest, shortest way to count capital letters in a string with php?-letters

Accepted answer
Score: 50
function count_capitals($s) {
  return mb_strlen(preg_replace('![^A-Z]+!', '', $s));
}

0

Score: 8
$str = "AbCdE";

preg_match_all("/[A-Z]/", $str); // 3

0

Score: 6

George Garchagudashvili Solution is amazing, but 11 it fails if the lower case letters contain 10 diacritics or accents.

So I did a small fix 9 to improve his version, that works also 8 with lower case accentuated letters:

public static function countCapitalLetters($string){

    $lowerCase = mb_strtolower($string);

    return strlen($lowerCase) - similar_text($string, $lowerCase);
}

You 7 can find this method and lots of other string 6 common operations at the turbocommons library:

https://github.com/edertone/TurboCommons/blob/70a9de1737d8c10e0f6db04f5eab0f9c4cbd454f/TurboCommons-Php/src/main/php/utils/StringUtils.php#L373

EDIT 2019

The 5 method to count capital letters in turbocommons 4 has evolved to a method that can count upper 3 case and lower case characters on any string. You 2 can check it here:

https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391

Read more info here:

https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php

And 1 it can also be tested online here:

https://turbocommons.org/en/app/stringutils/count-capital-letters

Score: 3

I'd give another solution, maybe not elegant, but 1 helpful:

$mixed_case = "HelLo wOrlD";
$lower_case = strtolower($mixed_case);

$similar = similar_text($mixed_case, $lower_case);

echo strlen($mixed_case) - $similar; // 4
Score: 0

It's not the shortest, but it is arguably 5 the simplest as a regex doesn't have to 4 be executed. Normally I'd say this should 3 be faster as the logic and checks are simple, but 2 PHP always surprises me with how fast and 1 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";

More Related questions