Mark
Mark

Reputation: 647

Using php to count the number of uppercase letters in a string

Using PHP, I need to determine if a string contains "more than one" uppercase letter.

The sentence above contains 4 uppercase letters: PHP and I

The count of how many uppercase letters is what I need. In the above sentence, that count would be 4.

I tried the preg_match_all below, but it only lets me know if any uppercase letters were found, even if the result is only one, or any number of occurrences.

if ( preg_match_all("/[A-Z]/", $string) === 0 )
{
     do something
}

Upvotes: 1

Views: 1668

Answers (3)

Funk Forty Niner
Funk Forty Niner

Reputation: 74219

Borrowed from https://stackoverflow.com/a/1823004/ (which I did upvote) and modified:

$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>";
}

Will output:

Total number of uppercase letters found: 5
from the string: Peter wenT To the MarkeT: PTTMT

Upvotes: 2

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

You can do something like this:

if(strlen(preg_replace('![^A-Z]+!', '', $string)) > 1){
    echo "more than one upper case letter";
}

Upvotes: 0

pguardiario
pguardiario

Reputation: 55002

if(preg_match('/[A-Z].*[A-Z]/', $string)){
  echo "there's more than 1 uppercase letter!";
}

Upvotes: 0

Related Questions