What is back refernces

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Naeem
Forum Commoner
Posts: 31
Joined: Tue Jul 07, 2009 12:48 pm

What is back refernces

Post by Naeem »

Hello to all
I want know what is back reference meaning in regular expressions.
Thanks.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: What is back refernces

Post by superdezign »

A backreference is when you re-use part of your regex. So, let's say you wanted to match a full HTML tag, opening and closing:

Code: Select all

<tag>content</tag>
You'd want to find any tag, and then match it with it's closing tag. Opening tag is the '<' character, the tag name, and the '>' character; closing tag is the '</' characters, tag name, and the '>' character. So, this regex would match a basic tag:

Code: Select all

<([A-Za-z]+)>.*?</\\1>
In PHP, we need two slashes before the '1' in order to create the escaping slash character, but normally you'd only use 1 slash.

Basically, the slash then the number matches the nth matched data. Each match is in parentheses, so \1 matches the first match in parentheses, the '([A-Za-z]+)'.

Note that in HTML parsing, this regex can't handle nesting very well.
Post Reply