Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

which is compared to user input. It will be instructive to examine this expression in
detail. It starts with a carat. This causes the expression to match only from the beginning
of the evaluated string. If this were left out, the zip code could be preceded by any
number of characters, such as abc12345-1234, and still be a valid match. Likewise,
the dollar sign at the end of the expression matches the end of the string. This stops
matching of strings like 12345-1234abc. The combination of using a carat and a
dollar sign allows us to match only exact strings.


The first subexpression is ([0-9]{5}). The square-bracketed range allows only
characters from zero to nine. The curly braces specify that there must be exactly five of
these characters.


The second subexpression is (-[0-9]{4})?. Like the first, it specifies exactly four
digits. The dash is a literal character that must precede the digits. The question mark
specifies that the entire subexpression may match once or not at all. This makes the four-
digit extension optional.


You can easily expand this idea to check phone numbers or dates. Regular expressions
provide a neat way of checking variables returned from forms. Consider the alternative of
nesting if statements and searching strings with the strpos function.


You may also choose to have subexpression matches returned in an array. This is useful
in situations where you need to break a string into components. The string a browser uses
to identify itself is a good string for this method. Encoded in this string are the browser's
name, version, and the type of computer it's running on. Pulling this information out into
separate variables will allow you to customize your site based on the capabilities of the
browser.


Listing 16.3 is a script for creating a set of variables that aid in cloaking a site for a
particular browser. For the purpose of illustration, we will customize a link based on the
browser being used. If the user visits the page with Netscape Navigator, we will provide a
link to the download page for Microsoft Internet Explorer. Otherwise, we'll put a link to
Netscape's download page. This is an example of customizing content, but the same
method can be used to decide whether to use advanced features or not.


Listing 16.3 Evaluating HTTP_USER_AGENT

Free download pdf