What is the best way to see if a string contains mostly capital letters?
The string may also contain symbols, spaces, numbers, so would still want it to return true in those cases.
For example: I can check if a strings is ALL-CAPS by something similar to this:
if (strtoupper($str) == $str) { /* its true */ }
But what if we need to determine if a string is 80% or more ALL-CAPs.
THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn! -> true
The 15 Small Brown Foxes JUMP Into the Burning Barn! -> false
I can loop though all the characters, checking them individually, but thats seems a bit wasteful imho.
Is there a better way?
$countUppercase = strlen(preg_replace('/[^A-Z]+/', '', $str));
// or: mb_strlen(...)
... and then divide by strlen($str)
A simple for loop should give the best performance
$numUpper = 0;
for ($i = 0; $i < strlen($str); $i++){
if (ctype_upper($str[$i])) {
$numUpper++;
}
}
return $numUpper;
Another option could be using preg_match_all which returns the number of full pattern matches and mb_strlen.
The pattern \p{Lu} matches an uppercase letter that has a lowercase variant.
For example:
function mostlyUpperInString($s, $threshold) {
return preg_match_all("/\p{Lu}/u", $s) / mb_strlen($s) > $threshold;
}
function moreUpperThanLower($s, $threshold) {
return preg_match_all("/\p{Lu}/u", $s) / preg_match_all("/\P{Lu}/u", $s) > $threshold;
}
$strings = [
"THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn!",
"The 15 Small Brown Foxes JUMP Into the Burning Barn!"
];
foreach ($strings as $str) {
echo $str . " -> 80% mostlyUpperInString: ". (mostlyUpperInString($str, 0.8) ? "true" : "false") . PHP_EOL;
echo $str . " -> 80% moreUpperThanLower: ". (moreUpperThanLower($str, 0.8) ? "true" : "false") . PHP_EOL;
echo PHP_EOL;
}
Output
THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn! -> 80% mostlyUpperInString: false
THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn! -> 80% moreUpperThanLower: true
The 15 Small Brown Foxes JUMP Into the Burning Barn! -> 80% mostlyUpperInString: false
The 15 Small Brown Foxes JUMP Into the Burning Barn! -> 80% moreUpperThanLower: false
See a PHP demo.