John Davidson

Check if a String is mostly ALL CAPS in PHP

0 comments
Message:


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?



My Answer:
One way to check if a string is mostly all caps in PHP is to count the number of uppercase letters in the string and compare it to the total number of letters in the string. Here is an example code snippet to achieve this:

php
function isMostlyAllCaps($str) {
$totalLetters = strlen(preg_replace('/[^A-Za-z]/', '', $str));
$uppercaseLetters = strlen(preg_replace('/[^A-Z]/', '', $str));

if ($totalLetters == 0) {
return false;
}

$percentageUppercase = ($uppercaseLetters / $totalLetters) * 100;

return $percentageUppercase >= 80;
}

$str = "THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn!";
if (isMostlyAllCaps($str)) {
echo "The string is mostly all caps.";
} else {
echo "The string is not mostly all caps.";
}


This code snippet defines a function `isMostlyAllCaps` that takes a string as input and calculates the percentage of uppercase letters in the string. It then checks if the percentage of uppercase letters is 80% or more and returns true if it is, and false otherwise.

You can test this code snippet with the example string provided ("THE 15 SMALL BROWN FOXES JUMP INTO THE BURNING barn!") to see if it correctly identifies if the string is mostly all caps.

Rate this post

4 of 5 based on 8568 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us