繁体   English   中英

使用php计算字符串中大写字母的数量

[英]Using php to count the number of uppercase letters in a string

使用PHP,我需要确定一个字符串是否包含“多个”大写字母。

上面的句子包含4个大写字母:PHP和I

我需要多少个大写字母。 在上面的句子中,该数字为4。

我尝试了下面的preg_match_all,但它只让我知道是否找到了大写字母,即使结果只是一个或出现了多少次也是如此。

if ( preg_match_all("/[A-Z]/", $string) === 0 )
{
     do something
}

https://stackoverflow.com/a/1823004/借来( 我做了upvote )并进行了修改:

$string = "Peter wenT To the MarkeT";

$charcnt = 0;
$matches = array();
if (preg_match_all("/[A-Z]/", $string, $matches) > 0) {
  foreach ($matches[0] as $match) { $charcnt += strlen($match); }
}

printf("Total number of uppercase letters found: %d\n", $charcnt);

   echo "<br>from the string: $string: ";

foreach($matches[0] as $var){
   echo "<b>" . $var . "</b>";
}

将输出:

找到的大写字母总数:5
从字符串:Peter wenT到市场: PTTMT

if(preg_match('/[A-Z].*[A-Z]/', $string)){
  echo "there's more than 1 uppercase letter!";
}

您可以执行以下操作:

if(strlen(preg_replace('![^A-Z]+!', '', $string)) > 1){
    echo "more than one upper case letter";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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