Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

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

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_var($url, $key, $value) { 
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); 
$url = substr($url, 0, -1); 
if (strpos($url, '?') === false) { 
  return ($url . '?' . $key . '=' . $value); 
} else { 
  return ($url . '&' . $key . '=' . $value); 
} 
}

Not too familiar with regular expression stuff. I get the various parts to preg_replace but not 100% about the use of '$1$2$4' in the replacement part.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$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 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 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...