使用PHP,我需要确定字符串是否包含"多个"大写字母。
上面的句子包含4个大写字母:PHP和I
我需要的是计算多少个大写字母。在上面的句子中,这个数字是4。
我尝试了下面的preg_match_all,但它只让我知道是否找到了大写字母,即使结果只有一个或任何次数。
if ( preg_match_all("/[A-Z]/", $string) === 0 )
{
do something
}
借用自https://stackoverflow.com/a/1823004/(我投了赞成票)并修改了:
$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";
}