Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 only—no uppercase letters, no lowercase letters, and no numbers.

There is a list of regular expressions using character classes, along with the string they match—and whether or not a match is made—in Table 15-2.

Table 15-2. Regular expressions using character classes

Function 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! ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page