【问题标题】:simplest, shortest way to count capital letters in a string with php?用php计算字符串中大写字母的最简单、最短的方法?
【发布时间】:2010-12-06 04:34:40
【问题描述】:

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

【问题讨论】:

  • 如果你想作弊:strlen(strtoupper($str)) ;)
  • 最简单最优雅的!=代码高尔夫
  • str_replace(range('A', 'Z'), '', $str, $num_caps);回声 $num_caps;

标签: php count letters


【解决方案1】:
function count_capitals($s) {
  return mb_strlen(preg_replace('![^A-Z]+!', '', $s));
}

【讨论】:

  • 不适用于各种语言的特殊 utf-8 字符。
  • @emix 支持所有特殊字符(变音符号)的正则表达式是/[^\p{Lu}]/u
  • @emix、@Almino Melo,以及在使用/[^\p{Lu}]/u时将mb_strlen 用于多字节字符串
【解决方案2】:
$str = "AbCdE";

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

【讨论】:

    【解决方案3】:

    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
      

      【讨论】:

      • 似乎这个解决方案甚至适用于带有变音符号的大写字母。 +1
      【解决方案5】:

      它不是最短的,但可以说是最简单的,因为不必执行正则表达式。通常我会说这应该更快,因为逻辑和检查很简单,但 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";
      

      【讨论】:

      • 函数 count_capitals 快得多了。使用非常短的字符串 count_capitals 只会快一点,但使用“Lorem ipsum...”的第一段,运行 3000 次迭代需要 0.03 秒,而通过函数运行相同的字符串需要 1.8 秒 capital_letters 3000 次。
      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2021-06-08
      • 2013-08-10
      • 2011-10-02
      • 2020-01-04
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多