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

前端 未结 3 609
夕颜
夕颜 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 05:49

    Perl regular expression replacement uses match variables which are the parts inside of parentheses in the regular expression:

       $1   $2                      $3 $4
    '/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i'
    

    So, referring to $1 in the replacement string will substitute what was matched in the the first parentheses. $0 however will refer to the entire matching string.

    You can even match the parenthetical subsets inside of the regular expression itself using a backslash instead of a dollar sign. For instance, if you wanted to replace doubled words "the", or "and":

    preg_replace('/\b(the|and)\b\s*\1/', '$1', $sentence);
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-15 06:15

    The are place holders for each part of regex enclosed in parenthesis, they replace the part specified in regex.

    0 讨论(0)
提交回复
热议问题