tags:

views:

903

answers:

4

Hi, is there an easy way to count uppercase words within a string?

+5  A: 

You could use a regular expression to find all uppercase words and count them:

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

The expression \b is a word boundary so it will only match whole uppercase words.

Gumbo
should the digits also be in that character class, [A-Z0-9]. CAPS123 looks uppercase!
Sean A.O. Harney
Simplified it since `preg_match_all` does already return the number of matches.
Gumbo
+2  A: 

Shooting from the hip, but this (or something like it) should work:

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

countUppercase("Hello good Sir"); // 2
cpharmston
Sorry about all the edits; I've been programming in Python all morning and made a bunch of syntax errors.
cpharmston
A: 
$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;
    }
}
ghostdog74
+1  A: 
<?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.");
?>

Should work.

Bogdan Popa