Back references are a means to use a previous captured sub-expression in the regular expression itself. It can be useful in situations such as matching html tags where you want to match the ending tag when the starting tag is not known.
The syntax for back references is: `\1` or any digit above one, maximum number of back references allowed are 99.
<?php $pattern = '!<(.*?)>.*?</\1>!'; $string = 'some text <tag> text </tag> some text'; preg_match($pattern, $string, $matches); ?>
Back references must refer to capturing sub-expressions, they can not be used with non-capturing sub-expressions. The following will not work, it will raise an error.
$pattern = '!<(?:.*?)>.*?</\1>!';
because you are referencing a sub-expression which does not exist, as it was not captured. It is the same as matching a sub-expression which was not used because of another alternative being used as in the following
$pattern = '!(a|(bc))\1!';
This will not match if the string starts with `a` but will match if the string starts with `bc`.