Specifications

The second use is to validate customer email addresses in our application by encoding the stan-
dardized format of an email address in a regular expression. The format includes some
alphanumeric or punctuation characters, followed by an @ symbol, followed by a string of
alphanumeric and hyphen characters, followed by a dot, followed by more alphanumeric and
hyphen characters and possibly more dots, up until the end of the string, which encodes as fol-
lows:
^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$
The subexpression ^[a-zA-Z0-9_]+ means start the string with at least one letter, number, or
underscore, or some combination of those.
The @ symbol matches a literal @.
The subexpression [a-zA-Z0-9\-]+ matches the first part of the host name including alphanu-
meric characters and hyphens. Note that weve slashed out the hyphen because its a special
character inside square brackets.
The \. combination matches a literal ..
The subexpression [a-zA-Z0-9\-\.]+$ matches the rest of a domain name, including letters,
numbers, hyphens, and more dots if required, up until the end of the string.
A bit of analysis shows that you can produce invalid email addresses that will still match this
regular expression. It is almost impossible to catch them all, but this will improve the situation
a little.
Now that you have read about regular expressions, well look at the PHP functions that use
them.
Finding Substrings with Regular Expressions
Finding substrings is the main application of the regular expressions we just developed. The
two functions available in PHP for matching regular expressions are ereg() and eregi().
The ereg() function has the following prototype:
int ereg(string pattern, string search, array [matches]);
This function searches the search string, looking for matches to the regular expression in
pattern. If matches are found for subexpressions of pattern, they will be stored in the array
matches, one subexpression per array element.
The eregi() function is identical except that it is not case sensitive.
Using PHP
P
ART I
114
06 7842 CH04 3/6/01 3:41 PM Page 114