I have a function which fixes capitalization for those naughty users that insist on making everything UPPERCASE!
I want my function to only be called when a string contains an uppercase word of 3 or more uppercase letters.
Can this be done with a regex?
examples:
for example: I = false
, DEAL = true
, Welcome = false
Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter. In a character set a ^ character negates the following characters.
The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters.
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."
if (preg_match('/\b\p{L}*\p{Lu}{3}\p{L}*\b/u', $str)) {
// Naughty user!
}
will match any word that contains at least three uppercase letters. It doesn't matter whether the word starts with an uppercase or lowercase letter, so it would match, for example iTUNES
or StackOVERflow
as complete words.
If you want to restrict yourself to words that consist entirely of uppercase characters, three or more, then use
if (preg_match('/\b\p{Lu}{3,}\b/u', $str)) {
// Naughty user!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With