15.2. Regexp Character Classes Regular expressions allow you to form character classes of words using brackets [ and ]. For example, you can define a character class [Ff] that will match "F" or "f". You can also use character classes to accept ranges; for example, [A-Z] will accept all uppercase letters, [A-Za-z] will accept all letters, whether uppercase or lowercase, and [a-z0-9] will accept lowercase letters and numbers only. At the beginning of a character class, the caret symbol ^ means "not," therefore [^A-Z] will accept everything that is not an uppercase letter, and [^A-Za-z0-9] will accept symbols onlyno uppercase letters, no lowercase letters, and no numbers. There is a list of regular expressions using character classes, along with the string they matchand whether or not a match is madein Table 15-2. Table 15-2. Regular expressions using character classesFunction call | Result |
---|
preg_match("/[Ff]oo/", "Foo") | True | preg_match("/[^Ff]oo/", "Foo") | False; the regexp says "Anything that is not F or f, followed by "oo". This would match "too", "boo", "zoo", etc. | preg_match("/[A-Z][0-9]/", "K9") | True | preg_match("/[A-S]esting/", "Testing") | False; the acceptable range for the first character ends at S | preg_match("/[A-T]esting/", "Testing") | True; the range is inclusive | preg_match("/[a-z]esting[0-9][0-9]/", "TestingAA") | False | preg_match("/[a-z]esting[0-9][0-9]/", "testing99") | True | preg_match("/[a-z]esting[0-9][0-9]/", "Testing99") | False; case sensitivity! | preg_match("/[a-z]esting[0-9][0-9]/i", "Testing99") | True; case problems fixed with /i | preg_match("/[^a-z]esting/", "Testing") | True; first character can be anything that is not a, b, c, d, e, etc. (lowercase) | preg_match("/[^a-z]esting/i", "Testing") | False; the range excludes lowercase characters only, so you would think T would be fine. However, the "i" at the end makes it insensitive, which turns [^a-z] into [^a-zA-Z] |
The last one is a common mistake, so make sure you understand why it does not match. |