2009-07-25 65 views
2

有没有简单的方法来计算字符串中的大写字?PHP:计算字符串中的大写字

+0

非常感谢!这对我有用: 函数countUppercase($ str){ preg_match_all(“/ \ b [A-Z] [A-Za-z0-9] + \ b /”,$ str,$ matches); 返回计数($ matches [0]); } – paul4324 2009-07-25 13:24:06

回答

5

从臀部射击,但是这(或类似的东西)应该工作:

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

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

你可以使用正则表达式查找所有大写单词并计数:

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

表达\bword boundary所以将只匹配全大写单词。

+1

数字也应该在该字符类中,[A-Z0-9]。 CAPS123看起来大写! – 2009-07-25 12:39:14

+0

简化它,因为preg_match_all已经返回匹配数。 – Gumbo 2009-07-25 13:36:18

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

应该工作。

1

这将计数字符串中大写的数量,即使是一个字符串,它包括非字母数字字符

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

一个简单的解决办法是用的preg_replace剥离所有非大写字母然后与strlen的像这样算返回的字符串:

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

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