Page 586 - Beginning PHP 5.3
P. 586
Part III: Using PHP in Practice
By the way, notice that the expression string was surrounded by single quotes in this example, rather
than the usual double quotes. If the code had used double quotes, an extra backslash would have been
needed before the \1 (because PHP assumes \1 to be the ASCII character with character code 1 when
inside a double - quoted string):
preg_match( “/favoritePet\=(\w+).*\\1\=(\w+)/”, $myPets, $matches );
Character escaping issues like this have been known to trip up many a seasoned programmer, so this is
something to watch out for.
Matching Alternative Patterns
Regular expressions let you combine patterns (and subpatterns) with the | (vertical bar) character to
create alternatives. This is a bit like using the || (or) operator; if any of the patterns combined with the |
character match, the overall pattern matches.
The following pattern matches if the target string contains any one of the abbreviated days of the week
(mon – sun):
$day = “wed”;
echo preg_match( “/mon|tue|wed|thu|fri|sat|sun/”, $day ); // Displays “1”
You can also use alternatives within subpatterns, which is very handy. Here ’ s the earlier “ date detection ”
example, rewritten to be more precise:
echo preg_match( “/(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)” .
“\/\d{1,2}\/\d{2,4}/”, “jul/15/2006” ); // Displays “1”
Using Anchors to Match at Specified Positions
Often you ’ re interested in the position of a pattern within a target string, as much as the pattern itself. For
example, say you wanted to make sure that a string started with one or more digits followed by a colon.
You might try this:
echo preg_match( “/\d+\:/”, “12: The Sting” ); // Displays “1”
However, this expression would also match a string where the digits and colon are somewhere in the
middle:
echo preg_match( “/\d+\:/”, “Die Hard 2: Die Harder” ); // Displays “1”
How can you make sure that the string only matches if the digits and colon are at the start? The answer
is that you can use an anchor (also known as an assertion ), as follows:
548
9/21/09 6:17:54 PM
c18.indd 548
c18.indd 548 9/21/09 6:17:54 PM