【问题标题】:PHP: count uppercase words in stringPHP:计算字符串中的大写单词
【发布时间】:2009-07-25 12:28:25
【问题描述】:

有没有一种简单的方法来计算字符串中的大写单词?

【问题讨论】:

  • 非常感谢!这对我有用: function countUppercase($str){ preg_match_all("/\b[A-Z][A-Za-z0-9]+\b/",$str,$matches);返回计数($matches[0]); }
  • 这个问题太宽泛/不清楚,因为没有编码尝试,没有样本输入,没有预期的输出,没有上下文,没有研究证明。由于这个问题的措辞有些模棱两可,因此发布了执行不同操作的答案 - 这对研究人员不利。

标签: php count


【解决方案1】:

您可以使用正则表达式查找所有大写单词并计算它们:

echo preg_match_all('/\b[A-Z]+\b/', $str);

表达式\bword boundary,所以它只会匹配整个大写单词。

【讨论】:

  • 数字也应该属于那个字符类,[A-Z0-9]。 CAPS123 看起来是大写的!
  • 简化了它,因为preg_match_all 已经返回了匹配的数量。
【解决方案2】:

从臀部射击,但这个(或类似的东西)应该有效:

function countUppercase($string) {
     return preg_match_all(/\b[A-Z][A-Za-z0-9]+\b/, $string)
}

countUppercase("Hello good Sir"); // 2

【讨论】:

  • 对所有的编辑感到抱歉;我整个早上都在用 Python 编程,犯了一堆语法错误。
【解决方案3】:
<?php
function upper_count($str)
{
    $words = explode(" ", $str);
    $i = 0;

    foreach ($words as $word)
    {
        if (strtoupper($word) === $word)
        {
            $i++;
        }
    }

    return $i;
}

echo upper_count("There ARE two WORDS in upper case in this string.");
?>

应该可以。

【讨论】:

    【解决方案4】:

    这将计算字符串中大写字母的数量,即使对于包含非字母数字字符的字符串也是如此

    function countUppercase($str){ 
         preg_match_all("/[A-Z]/",$str,$matches); 
         return count($matches[0]);
    }
    

    【讨论】:

      【解决方案5】:

      一个简单的解决方案是用 preg_replace 去除所有非大写字母,然后用 strlen 计算返回字符串,如下所示:

      function countUppercase($string) {
          echo strlen(preg_replace("/[^A-Z]/","", $string));
      }
      
      echo countUppercase("Hello and Good Day"); // 3
      

      【讨论】:

        【解决方案6】:
        $str = <<<A
        ONE two THREE four five Six SEVEN eighT
        A;
        $count=0;
        $s = explode(" ",$str);
        foreach ($s as $k){
            if( strtoupper($k) === $k){
                $count+=1;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-12
          • 1970-01-01
          • 1970-01-01
          • 2016-09-06
          • 2010-10-16
          • 2023-03-21
          相关资源
          最近更新 更多