PHP Regular Expressions Backreference

Description

We can take the text that matched a subpattern and use it elsewhere in the expression.

Backreferences allow you to create quite powerful, adaptable regular expressions.

Syntax

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.

Example 1


<?PHP//w w  w  .jav a  2 s.  c  om
$my = "favorite=PHP, Javascript=front, PHP=web"; 
preg_match( '/favorite\=(\w+).*\1\=(\w+)/', $my, $matches ); 

echo $matches[2] . " called " . $matches[1] . ".";
?>

It first looks for the string "favorite=" followed by one or more word characters:

/favorite\=(\w+)

Next the expression looks for zero or more characters of any type, followed by the string that the first subpattern matched, followed by an equals sign, followed by one or more word characters:

.*\1\=(\w+)

Finally, the code displays the results of both subpattern matches in a message to the user.

The code above generates the following result.





















Home »
  PHP Tutorial »
    Development »




Environment
Error
Hash
Include
Locale
Math
Network
Output
Reflection
PHP Regular Expressions