使用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到MarkeT:PTTMT
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句