By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Count capital letters of string with PHP

How to easily count the capital letters in a string.

Edited: 2014-12-28 04:01

Capital letters can be a pain sometimes, some users just LiKe To meSS ArounD!

How about blocking suspect use of caps? An easy way to do this, would be to use preg_replace inside of strlen. Preg_replace will remove non-caps from the string, and strlen will return the number of remaining caps.

This is a useful way to count capital letters in PHP.

The regular expression

The regex that we will use with Preg_replace.


This regex will replace all characters, except for the capital letters (A to Z). If you need more then those, like Æ Ø AND Å, simply include them after the A-Z part.


Count capital letters

Placing the Preg_replace inside of strlen will work.

strlen(preg_replace('/[^A-Z]+/', '', $string));

Count caps function

But why not create a function now that we are at it? The below function will return the number of caps of a string.

function CountCaps($string) {
  return strlen(preg_replace('/[^A-Z]+/', '', $string));