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)Read here
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.
Also in PHP