php-regexHow to use backreference in PHP regex?
Backreferences in PHP regex are used to match the same text as previously matched by a capturing group.
Example code
$string = 'The quick brown fox jumps over the lazy dog.';
$pattern = '/(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+over\s+\1/';
if (preg_match($pattern, $string, $matches)) {
echo "Matched: {$matches[0]}\n";
echo "1: {$matches[1]}\n";
echo "2: {$matches[2]}\n";
echo "3: {$matches[3]}\n";
echo "4: {$matches[4]}\n";
}
Output example
Matched: The quick brown fox jumps over the
1: The
2: quick
3: brown
4: fox
Code explanation
$string
: This is the string that will be tested against the regular expression.$pattern
: This is the regular expression that will be used to match the string. The backreference\1
is used to match the same text as previously matched by the first capturing group.preg_match()
: This is the function used to match the string against the regular expression.$matches
: This is an array that will contain the matches found by the regular expression.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a double quote in PHP regex?
- How to use PHP regex to match URL path?
- How to get last matched occurrence in PHP regex?
- How to use PHP regex with zero or more occurrences?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to match a space using PHP regex?
- How to use an "or" condition in PHP regex?
See more codes...