PHP中最简单、最短的方法来计算字符串中大写字母的数量是什么?

23

我正在寻找一种最短、最简单、最优雅的方法来计算给定字符串中大写字母的数量。


6
如果您想作弊:strlen(strtoupper($str)) ;) (提示:该语句是一段计算字符串长度并将其转换为大写字母后的长度值的代码,末尾的“;)”可能是一个眼神表情或无意义的字符。) - Steven Mercatante
最简单和最优雅的不等于代码高尔夫。 - Sam Harwell
4
str_replace(range('A', 'Z'), '', $str, $num_caps); 将字符串$str中的所有大写字母替换为空字符串,并将替换的次数存储在变量$num_caps中。echo $num_caps;输出$num_caps的值。 - GZipp
5个回答

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

无法处理来自各种语言的特殊UTF-8字符。 - Mike Doe
@emix 支持所有特殊字符(变音符号)的正则表达式为 /[^\p{Lu}]/u - Almino Melo
1
请使用 mb_strlen 处理多字节字符串,当您使用 /[^\p{Lu}]/u 时。@emix,@Almino Melo - Beta Projects

10
$str = "AbCdE";

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

5

George Garchagudashvili的解决方案非常出色,但如果小写字母含有变音符或重音符号,则无法正常工作。

因此,我对他的版本进行了小修补,以便也能处理小写带重音的字母:

public static function countCapitalLetters($string){

    $lowerCase = mb_strtolower($string);

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

您可以在turbocommons库中找到此方法和许多其他常见的字符串操作:https://github.com/edertone/TurboCommons/blob/70a9de1737d8c10e0f6db04f5eab0f9c4cbd454f/TurboCommons-Php/src/main/php/utils/StringUtils.php#L373 2019年编辑 Turbocommons中计算大写字母的方法已经发展成一种可以计算任何字符串中大写字母和小写字符的方法。您可以在这里检查它:https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391 阅读更多信息:https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php 您还可以在此处在线测试:https://turbocommons.org/en/app/stringutils/count-capital-letters

4
我会给出另一种解决方案,可能不够优美,但很有用:

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

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

echo strlen($mixed_case) - $similar; // 4

3
似乎这个解决方案甚至适用于带有变音符号的大写字母。+1 - LittleTiger

0

这可能不是最短的方法,但可以说是最简单的方法,因为无需执行正则表达式。通常我会说这应该更快,因为逻辑和检查很简单,但是PHP总是让我惊讶,有时与其他东西相比速度快,有时速度慢。

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

3
函数 count_capitals 远比函数 capital_letters 快。对于非常短的字符串,count_capitals 只比后者快一点点,但对于“Lorem ipsum…” 的第一个段落,运行 3000 次迭代需要 0.03 秒,而将同样的字符串通过函数 capital_letters 运行 3000 次则需要 1.8 秒。 - user494215

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接