Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...