使用PHP,我需要確定一個字符串是否包含「多於一個」大寫字母。使用PHP來計算字符串中大寫字母的數量
這句話上面包含4個大寫字母:PHP和我
多少大寫字母的數量是我所需要的。在上面的句子中,該數字爲4.
我嘗試了下面的preg_match_all,但它只是讓我知道是否發現了任何大寫字母,即使結果只有一個,或者任何次數。
if (preg_match_all("/[A-Z]/", $string) === 0)
{
do something
}
使用PHP,我需要確定一個字符串是否包含「多於一個」大寫字母。使用PHP來計算字符串中大寫字母的數量
這句話上面包含4個大寫字母:PHP和我
多少大寫字母的數量是我所需要的。在上面的句子中,該數字爲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
從字符串:彼得去市場:PTTMT
這很好。 $ matches在我以前的嘗試中,我認爲$ matches是返回多少匹配的計數,但自從發現它返回一個多維數組。非常感謝! – Mark
@Mark非常歡迎馬克,*歡呼聲* –
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";
}
你可以像'如果(preg_match_all( 「/ [AZ] /」,$字符串,$匹配)> 1)'。 [preg_match_all](http://php.net/manual/en/function.preg-match-all.php)返回全模式匹配的數量。注意:如果沒有第三個參數,則會生成警告。 – bansi
bansi的以上評論是IMO的最佳解決方案。 –