Counting the number of Upper-Case Letters in a String - PHP
The first lesson on this blog is a tutorial on how to count the number of Upper Case letters in a given string. Thanks to the number functions in PHP, it was done without much stress.
The PHP functions to use are “preg_match_all” and “count”.
preg_match_all
(This PHP Function searches all matches for the supplied pattern and stores them in the supplied array)
How to initialize the function
int preg_match_all(pattern, subject, matches[, order]);
count
This PHP function returns the number of elements in a variable or an array.
How to initialize the function
int count(variable);
The Code:
<?php
//$your_string - the variable which stores the main string you are going to do the search on
// $total_upper_case_count - the variable which stores the count of all upper case numbers
//$your_match - the variable (array) which stores all the matches
$your_string = “This Is Where Your Main String Goes”;
preg_match_all(’/[A-Z]/’, $your_string, $your_match) ;
$total_upper_case_count = count($your_match [0]);
echo “Total Upper Case Count = ” . $total_upper_case_count;
?>
This example will give this Result:
Total Upper Case Count = 7
Doing the Opposite:
On the other hand if you want to RATHER COUNT THE TOTAL NUMBER OF LOWER-CASE LETTERS IN THE STRING, you will just need to edit the code preg_match_all(’/[A-Z]/’, $your_string, $your_match) ; by changing ‘/[A-Z]/’ to ‘/[a-z]/’















