PHP:计算字符串中的大写单词

时间:2009-07-25 12:28:25

标签: php count

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

6 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:5)

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

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

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

答案 2 :(得分:2)

<?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.");
?>

应该工作。

答案 3 :(得分:1)

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

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

答案 4 :(得分:1)

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

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

echo countUppercase("Hello and Good Day"); // 3

答案 5 :(得分:0)

$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;
    }
}