[英]Using php to count the number of uppercase letters in a string
Using PHP, I need to determine if a string contains "more than one" uppercase letter. 使用PHP,我需要确定一个字符串是否包含“多个”大写字母。
The sentence above contains 4 uppercase letters: PHP and I 上面的句子包含4个大写字母:PHP和I
The count of how many uppercase letters is what I need. 我需要多少个大写字母。 In the above sentence, that count would be 4. 在上面的句子中,该数字为4。
I tried the preg_match_all below, but it only lets me know if any uppercase letters were found, even if the result is only one, or any number of occurrences. 我尝试了下面的preg_match_all,但它只让我知道是否找到了大写字母,即使结果只是一个或出现了多少次也是如此。
if ( preg_match_all("/[A-Z]/", $string) === 0 )
{
do something
}
Borrowed from https://stackoverflow.com/a/1823004/ ( which I did upvote ) and modified: 从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>";
}
Will output: 将输出:
Total number of uppercase letters found: 5 找到的大写字母总数:5
from the string: Peter wenT To the MarkeT: PTTMT 从字符串:Peter wenT到市场: PTTMT
if(preg_match('/[A-Z].*[A-Z]/', $string)){
echo "there's more than 1 uppercase letter!";
}
You can do something like this: 您可以执行以下操作:
if(strlen(preg_replace('![^A-Z]+!', '', $string)) > 1){
echo "more than one upper case letter";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.