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
2009-07-25 12:32:41
should the digits also be in that character class, [A-Z0-9]. CAPS123 looks uppercase!
Sean A.O. Harney
2009-07-25 12:39:14
Simplified it since `preg_match_all` does already return the number of matches.
Gumbo
2009-07-25 13:36:18
+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
2009-07-25 12:33:07
Sorry about all the edits; I've been programming in Python all morning and made a bunch of syntax errors.
cpharmston
2009-07-25 12:49:33
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
2009-07-25 12:35:22
+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
2009-07-25 12:37:52