What does the $1$2$4 mean in this preg_replace?

前端 未结 3 610
夕颜
夕颜 2020-12-15 05:26

Got this function for ammending the query string and was wondering what the replacement part of the pre_replace meant (ie- $1$2$4).

function add_querystring_         


        
3条回答
  •  自闭症患者
    2020-12-15 06:05

    $1, $2... $n in regular expression replaces are references to the matches wrapped in parenthesis. $0 would be the entire match, $1 would be the first parenthesized capture, $2 would be the second, etc.

    • $1 is a reference to whatever is matched by the first (.*)
    • $2 is a reference to (\?|&)
    • $4 is a reference to the second (.*)

    See the docs, specifically the replacement argument of the function:

    replacement may contain references of the form \n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. To use backslash in replacement, it must be doubled ("\\" PHP string).

提交回复
热议问题