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

php check if string contains uppercase and lowercase
program to count the number of numerals uppercase, lowercase and special character in a given string
uppercase validation in php
php isupper
php is lowercase
preg_replace

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

function count_capitals($s) {
  return strlen(preg_replace('![^A-Z]+!', '', $s));
}

Count Capital and Small Letters in PHP by Jake R. Pomperada, PHP 5, PHP 7). str_word_count — Return information about words used in a string This simple utf-8 word count function (it only counts) * is a bit faster then  Counts the number of words inside string.If the optional format is not specified, then the return value will be an integer representing the number of words found. . In the event the format is specified, the return value will be an array, content of which is dependent on the form

$str = "AbCdE";

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

str_word_count - Manual, Returns string with all alphabetic characters converted to uppercase. The convential way to express a 'ß' in an uppercase string is "SS". can never be capitalized — the following simple function can be used to capitalize text in Irish. strtoupper · strtr · substr_​compare · substr_​count · substr_​replace · substr · trim  Using PHP to show how many letters in a word? Is there a way to find out how many of a certain letter are in variables with php? e.g. $5 = ‘dinosaurs’; So it somehow echos how many of each letter there is? e.g. 1-d 1-i 1-n 1-o 2-s 1-a 1-u 1-r There is a built-in PHP function called count_chars(). However, it will count everything — spaces

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:

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

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:

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 it can also be tested online here:

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

strtoupper - Manual, ucfirst ( string $str ) : string. Returns a string with the first character of str capitalized, if that character is alphabetic. $count = count ($string); for ($i = 0; $i < $count; If there's a shorter, simpler way to do it, feel free to inform me. (​Emphasis on  Input string: "AAAbbCCddEe" Output: Number of uppercase characters: 6 Number of lowercase characters: 5. In this code we have two inputs: An int input (no. of test cases or more clearly the number of strings user wants to check (say 5 i.e user wants to check 5 strings and the program will continue for 5 inputs).

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

ucfirst - Manual, your function in recursive form proved to be slightly faster and it returns false (as If you reference a string with an offset like you do with an array, the character at that offset will be return. for ($x=0; $x < count($getvarkeys); $x++) { Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds: if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).

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";

String Functions - Manual, The tested string. Return Values ¶. Returns TRUE if every character in text is an uppercase letter in the current locale. In response to hackajar <matt> yahoo <trot> com, No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return.

ctype_upper - Manual, ucwords — Uppercase the first character of each word in a string This doesn't alter the content in any way other than changing case." The fix is simple however, and merely requires fine-tuning the regular this function using join(), array_map() and explode() was fastest. $count = sizeof($textbad); The simplest way to specify a string is to enclose it in single quotes (the character '). To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\).

ucwords - Manual, SORT_STRING Type Compares items as strings. Before reloading it in your browser, make a note of the position of several items (it's probably easiest to do it with sequence starts with the first character and works through each one in order. k; for ($i=0;$i<count($date);$i++) { // Convert date to timestamp and format  PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0'). In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string. For example, in PHP: strlen( "te\0st" ) = 5 In C, the same call would return 2.

Foundation PHP 5 for Flash, The string variables can contain alphanumeric characters. Creating Strings Using Single quotes: The simplest way to create a string is to use single quotes. strtoupper, Used to convert all string characters to upper case letters, echo strlen, The string length function is used to count the number of character in a string. Put spaces between words starting with capital letters You are given an array of characters which is basically a sentence. However there is no space between different words and the first letter of every word is in uppercase.

Comments
  • If you'd like to cheat: strlen(strtoupper($str)) ;)
  • Simplest and most elegant != code golf
  • str_replace(range('A', 'Z'), '', $str, $num_caps); echo $num_caps;
  • Won't work with special utf-8 characters from variety of languages.
  • Seems like this solution would work even for capital letters with diacritics on them. +1
  • Function 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.