简体   繁体   中英

PHP: count uppercase words in string

有没有一种简单的方法来计算字符串中的大写单词?

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.

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
<?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.

A simple solution would be to strip all non-uppercase letters with preg_replace and then count the return string with strlen like so:

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

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

This would count the number of uppercase within a string, even for a string that include non-alphanumeric characters

function countUppercase($str){ 
     preg_match_all("/[A-Z]/",$str,$matches); 
     return count($matches[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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM