PHP Regex matches a word or group of words in all uppercase letters

How can I use a regular expression to match a word or groups of words that are in capital letters?

I believe that I solved the problem halfway, although this may not be the case.

I try to catch one word in all caps, or two or three - basically, if they are in a row, I want them to be captured as a group, and not as every word.

eg.:
"HAPPY BIRTHDAY TOMMY" does not match and returns [0] -> HAPPY, [1] -> BIRTHDAY, [2] -> TOMMY , and the whole group, for example [0] -> HAPPY BIRTHDAY TOMMY .

The code I use below matches β€œHAPPY BIRTHDAY” together, or just β€œTOMMY”, but not all together.

 [AZ]{1,}\s[AZ]{1,}|\b[AZ]{1,}\b 
+4
source share
4 answers

You can use regex:

 (?=[AZ])([AZ\s]+) 

Look it up

+5
source

I am sure I fully understand what you need, but in order to group, you must use brackets (). try the following:

 ([AZ]+)\b([AZ]+)\b([AZ]+)\b 

This should capture three consecutive words of all caps.

+1
source

If I understand you correctly, this should do the trick /([AZ]\s?)+/ . This should catch sequences such as HAPPY BIRTHDAY TOMMY as a set and HAPPY BIRTHDAY tommy BOY as two sets ("HAPPY BIRTHDAY" and "BOY").

+1
source

How about this

 $str = "My test sentence HAPPY BIRTHDAY TOMMY this is lower case an UPPERCASE more lowercase"; if (preg_match_all('/\\b(?=[AZ])[AZ ]+(?=\\W)/',$str,$match)) { var_dump($match[0]); } 

result

array (2) {[0] => string (20) "HAPPY BIRTHDAY TOMMY" 1 => string (9) "UPPERCASE"}

Using lookahead at the end ensures that there are no spaces at the end, as this will happen if the word boundary is used, as well as the next word.

See here at Regexr

+1
source

Source: https://habr.com/ru/post/1380526/


All Articles