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

前端 未结 3 614
夕颜
夕颜 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);
    

提交回复
热议问题