I need bit of help in understanding a bit of regular expression . I saw code like
preg_match("/^
(1[-\s.])? # optional '1-', '1.' or '1'
( \( )? # optional opening parenthesis
\d{3} # the area code
(?(2) \) ) # if there was opening parenthesis, close it
[-\s.]? # followed by '-' or '.' or space
\d{3} # first 3 digits
[-\s.]? # followed by '-' or '.' or space
\d{4} # last 4 digits
$/x",$number)
i understood all but did not understand how does (?(2) \) )
really work... wht does ? and (2) in tht represent.
question update...
i read all your answers .. when i change the code like
preg_match("/^
(1[-\s.])? # optional '1-', '1.' or '1'
\d{3} # the area code
( \( )? # optional opening parenthesis
(?(3) \) ) # if there was opening parenthesis, close it
[-\s.]? # followed by '-' or '.' or space
\d{3} # first 3 digits
[-\s.]? # followed by '-' or '.' or space
\d{4} # last 4 digits
$/x",$number)
i get error like
Compilation failed: reference to non-existent subpattern
is there anythign wrong with the code?
(2) means the condition # 2 or you can say second capturing group which means condition in second ()
.It means if there is (
then there must b )
(?(1)then|else)
Means If the first capturing group took part in the match attempt thus far, the "then" part must match for the overall regex to match. If the first capturing group did not take part in the match, the "else" part must match for the overall regex to match.
eg: (a)?(?(1)b|c) matches ab, the first c and the second c in babxcac
(2)
means second matched fragment, from here: ( \( )?
. So the whole line works this way: if the second fragment was matched (means there was opening parenthesis), then we need to make sure there is closing parenthesis.
Guess it says what it does, looking for an area code which is stored in the 2nd result and if so, it also should be closed. This means this probably works as some kind of 'if result-2 is valid => close, else => nothing'.
Regular Expressions are not my best friends, so I hope I'm right.. but I also have difficulties explaining/creating them, so perhaps anyone could teach me a thing here now ;-)
By the way, if you google for a 'PHP Regular Expression Cheat Sheet', there are quiet some results that might be of your interest, at least they are interesting for me.