Square brackets ([]) are used to specify a range of possible values. This may take the
form of a list of legal characters. A range may be specified using the dash character (-).
If the list or range is preceded by a carat (^), the meaning is taken to be any character not
in the following list or range. Take note of this double meaning for the carat.
In addition to lists and ranges, square brackets may contain a character class. These class
names are further surrounded by colons, so that to match any alphabetic character you
write [:alpha:]. The classes are alnum, alpha, blank, cntrl, digit,
graph, lower, print, punct, space, upper, and xdigit. You may
wish to look at the man page for ctype to get a description of these classes.
Finally, two additional square bracket codes specify the beginning and ending of a word.
They are [:<:] and [:>:], respectively. A word in this sense is defined as any
sequence of alphanumeric characters and the underscore characters. Table 16-3 shows
examples of using square brackets.
Using Regular Expressions in PHP Scripts
The basic function for executing regular expressions is ereg. This function evaluates a
string against a regular expression, returning TRUE if the pattern described by the regular
expression appears in the string. In this minimal form, you can check that a string
conforms to a certain form. For example, you can ensure that a U.S. postal zip code is in
the proper form of five digits followed by a dash and four more digits. Listing 16.2
demonstrates this idea.
Table 16-3. Square Brackets in Regular Expressions
Sample Description
a.c Matches aac, abc, acc, ... — Any three-character string beginning with
an a and ending with a c.
^a. (^) Matches any string starting with an a.
[a-c]x$ Matches x, ax, bx, abax, abcx — Any string of letters from the first
three letters of the alphabet followed by an x.
b[ao]y (^) Matches only bay or boy.
[^Zz]{5} Matches any string, five characters long, that does not contain either
an upper- or lowercase z.
[[:digit:]]Matches any digit, equivalent to writing [0-9].
[[:<:]]a.* (^) Matches any word that starts with a.
Listing 16.2 Checking a ZIP Code