2009-07-25 64 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