在PHP中不使用RegEx计算大写和小写字母[关闭]
How do I count Uppercase and Lowercase letters and numbers in a string without using regular expressions?
如何使用正则表达式计算字符串不带 strong>的大写和小写字母和数字 ? p> div>
$string = "HelLo wOrlD";
$lowerCase = strtolower($string);
$upperCase = strtoupper($string);
$lowerDiff = similar_text($string, $lowerCase);
$upperDiff = similar_text($string, $upperCase);
echo "Capital:" . (strlen($string) - $lowerDiff); // 4
echo "<br>";
echo "Lowercase:" . (strlen($string) - $upperDiff); // 6
Try these functions:
<?
function count_uppercase($mixed_case) {
$lower_case = strtolower($mixed_case);
$similar = similar_text($mixed_case, $lower_case);
return strlen($mixed_case)-$similar;
}
function count_lowercase($mixed_case) {
$upper_case = strtoupper($mixedcase);
$similar = similar_text($mixed_case, $upper_case);
return strlen($mixed_case)-$similar;
}
?>
These functions make a new variable of whatever string and converts them all to either uppercase or lowercase (depending on which function you use) then compares the similarities between the strings, and returns the number of differences.
As an added bonus, this should also work with strings with diacritics in them.
Here is one way leveraging count_chars()
, array_filter()
, and array_sum()
. There will be many ways to tackle this one.
This method will get the byte values for each letter, filter against them (ascii table), then sum up the values.
$string="HelLo wOrlD";
$chars=count_chars($string,1);
$uppers=array_sum(array_filter($chars,function($k){return in_array($k,range(65,90));},ARRAY_FILTER_USE_KEY));
var_export($uppers);
echo "
";
$lowers=array_sum(array_filter($chars,function($k){return in_array($k,range(97,122));},ARRAY_FILTER_USE_KEY));
var_export($lowers);
Output:
4
6
Here is another which offers the same result:
$string="HelLo wOrlD";
$upper=$lower=0;
foreach(str_split($string) as $c){
if(ctype_upper($c)){
++$upper;
}elseif(ctype_lower($c)){
++$lower;
}
}
echo "Uppers = $upper, Lowers = $lower";
Here is another:
$string="HelLo wOrlD";
$array=str_split($string);
$uppers=sizeof(array_filter($array,'ctype_upper')); // 4
$lowers=sizeof(array_filter($array,'ctype_lower')); // 6
$string="HelLo wOrlD";
$array=str_split($string);
$uppers=sizeof(array_intersect($array,range('A','Z'))); // 4
$lowers=sizeof(array_intersect($array,range('a','z'))); // 6