Page 585 - Beginning PHP 5.3
P. 585
Chapter 18: String Matching with Regular Expressions
A side - effect of using subpatterns is that you can retrieve the individual subpattern matches in the
matches array passed to preg_match() . The first element of the array contains the entire matched text
as usual, and each subsequent element contains any matched subpatterns:
preg_match( “/(\d+\/\d+\/\d+) (\d+\:\d+.+)/”, “7/18/2004 9:34AM”, $matches );
echo $matches[0] . “ < br / > ”; // Displays “7/18/2004 9:34AM”
echo $matches[1] . “ < br / > ”; // Displays “7/18/2004”
echo $matches[2] . “ < br / > ”; // Displays “9:34AM”
Referring to Previous Subpattern Matches
You can take the text that matched a subpattern and use it elsewhere in the expression. This is known as
a backreference . Backreferences allow you to create quite powerful, adaptable regular expressions.
To include a subpattern ’ s matched text later in the expression, write a backslash followed by the
subpattern number. For example, you ’ d include the first subpattern ’ s matched text by writing \1 , and
the next subpattern ’ s matched text by writing \2 .
Consider the following example:
$myPets = “favoritePet=Lucky, Rover=dog, Lucky=cat”;
preg_match( ‘/favoritePet\=(\w+).*\1\=(\w+)/’, $myPets, $matches );
// Displays “My favorite pet is a cat called Lucky.”
echo “My favorite pet is a “ . $matches[2] . “ called “ . $matches[1] . “.”;
This code contains a string describing someone ’ s pets. From the string you know that their favorite pet is
Lucky, and that they have two pets: a dog called Rover and a cat called Lucky. By using a regular
expression with a backreference, the code can deduce that their favorite pet is a cat.
Here ’ s how the expression works. It first looks for the string “ favoritePet= ” followed by one or more
word characters ( “ Lucky ” in this case):
/favoritePet\=(\w+)
Next the expression looks for zero or more characters of any type, followed by the string that the first
subpattern matched ( “ Lucky “ ), followed by an equals sign, followed by one or more word characters
( “ cat ” in this example):
.*\1\=(\w+)
Finally, the code displays the results of both subpattern matches ( “ Lucky ” and “ cat ” ) in a message to
the user.
547
9/21/09 6:17:53 PM
c18.indd 547
c18.indd 547 9/21/09 6:17:53 PM

