When working with strings, occasionally we would want to check if any part of a word is uppercase or start of a word is an uppercase letter. This post provide a generic function that can be extended to match your needs.
For this post I will use the string below as my reference string
1 |
<em>$sentence = "This Is A String And Each Word Of This Sentence Starts With An Uppercase Letter";</em> |
Now let’s define our function that precisely checks a word for an Uppercase regardless of its position
1 2 3 |
function doesWordHasUppercase($word) { return (bool) preg_match("/[A-Z]/",$word); } |
preg_match() returns 1 if the pattern
matches given subject
, 0 if it does not, or FALSE
if an error occurred.
1 |
// Utilize the above function |
1 2 3 4 5 6 7 |
$words = preg_split("/\s{1,}/",$sentence); foreach ($words as $word) { if(doesWordHasUppercase($word)){ // do something } } |
Now let’s modify above function just to check if the first character is an Uppercase letter
1 2 3 4 5 6 |
function doesWordHasUppercase($word, $check_for_first_letter_only = false) { if($check_for_first_letter_only) return (bool) preg_match("/[A-Z]/", substr($word,0,1)); else return (bool) preg_match("/[A-Z]/",$word); } |
Now let’s utilise the function we wrote above
1 |
// Utilize the above function |
1 2 3 4 5 6 7 |
$words = preg_split("/\s{1,}/",$sentence); foreach ($words as $word) { if(doesWordHasUppercase($word,true)){ // we are passing second var value as true to check for the first letter only // do something, e.g. count the instances of first letter as uppercase and then compare against the number of words in a sentence to calculate percentage of words starting with uppercase letter etc } } |
I hope that in someway will be helpful to you, If you come across better method, I would like to know that,
Regards
Jas
Way to complicated.
$words=explode(‘ ‘,$sentence);
foreach( $words as $word ){
if( ucfirst($word) !== $word ) ===> no capital
}