cle*_*tus 42
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
Run Code Online (Sandbox Code Playgroud)
George Garchagudashvili 解决方案很棒,但如果小写字母包含变音符号或重音符号,它就会失败。
所以我做了一个小的修复来改进他的版本,这也适用于小写强调字母:
public static function countCapitalLetters($string){
$lowerCase = mb_strtolower($string);
return strlen($lowerCase) - similar_text($string, $lowerCase);
}
Run Code Online (Sandbox Code Playgroud)
您可以在 turbocommons 库中找到此方法和许多其他字符串常见操作:
编辑 2019
turbocommons 中计算大写字母的方法已经演变成一种可以计算任何字符串上大写和小写字符的方法。你可以在这里查看:
在此处阅读更多信息:
它也可以在这里在线测试:
https://turbocommons.org/en/app/stringutils/count-capital-letters