2009-10-13 57 views
12

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

+6

如果你想欺骗:strlen的(strtoupper($ STR));) – 2009-10-13 02:47:37

+0

最简单并且最优雅!= code高尔夫 – 2009-10-13 02:52:37

+4

str_replace(范围('A','Z'),'',$ str,$ num_caps); echo $ num_caps; – GZipp 2009-10-13 05:00:19

回答

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

cletus不能写代码。它从哪里来的? – 2014-12-22 14:29:34

+0

不适用于各种语言的特殊utf-8字符。 – 2017-11-04 20:30:48

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

就像在C! – alex 2010-11-02 02:04:38

+3

函数* count \ _capitals *到目前为止速度更快。使用非常短的字符串* count \ _capitals *只是更快一些,但是第一段“Lorem ipsum ...”运行3000次迭代需要0.03秒,而通过函数* capital \ _letters运行相同字符串需要1.8秒。 3000次。 – 2010-11-02 02:03:35

2

我给另一种解决方案,也许不是优雅,但有所帮助:

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

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

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

似乎这种解决方案即使对大写字母和变音符号也能工作。 +1 – LittleTiger 2016-10-24 04:33:13

2

乔治Garchagudashvili解决方案是惊人的,但如果小写字母包含变音符号或重音失败。

所以我做了一个小的修复,以提高自己的版本,与小写字母加剧也适用:

public static function countCapitalLetters($string){ 

    $lowerCase = mb_strtolower($string); 

    return strlen($lowerCase) - similar_text($string, $lowerCase); 
} 
相关问题