[英]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.