Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: count uppercase words in string

Tags:

php

count

is there an easy way to count uppercase words within a string?

like image 480
paul4324 Avatar asked Feb 21 '26 23:02

paul4324


2 Answers

You could use a regular expression to find all uppercase words and count them:

echo preg_match_all('/\b[A-Z]+\b/', $str);

The expression \b is a word boundary so it will only match whole uppercase words.

like image 134
Gumbo Avatar answered Feb 23 '26 14:02

Gumbo


Shooting from the hip, but this (or something like it) should work:

function countUppercase($string) {
     return preg_match_all(/\b[A-Z][A-Za-z0-9]+\b/, $string)
}

countUppercase("Hello good Sir"); // 2

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!