2009-07-25 9 views
2

文字列内の大文字を簡単に数える方法はありますか?PHP:文字列内の大文字を数える

+0

おかげでたくさん!これは私のために働いた: function countUppercase($ str){ preg_match_all( "/ \ b [A-Z] [A-Za-z0-9] + \ b /"、$ str、$ matches); リターンカウント($ matches [0]); } – paul4324

答えて

5

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

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

すべての編集が残念です。私は午前中にPythonでプログラミングをしていて、構文エラーがたくさんありました。 –

5

あなたはすべて大文字の単語を検索し、それらをカウントする正規表現を使用することができます。

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

表現\bword boundaryあるので、それだけで全体の大文字の単語と一致します。腰から撮影が、これは(またはそれのようなもの)が動作するはず

+1

数字もその文字クラス[A-Z0-9]でなければなりません。 CAPS123は大文字です! –

+0

'preg_match_all'は既にマッチの数を返しているので、簡略化しました。 – Gumbo

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 
関連する問題