Q . What is $1, $2 ... $n in preg_replace function in PHP?

Dev Singh. asked, Jun 29 ' 2017

 

I have a URL for replace some part. It is working fine but I didn't get what is $1$3 in the replacement string.

$pattern = '/^(https?://[^/]+/)([^/]+/)(.*)$/';
$replaceWith = '$1$3';
$string = 'http://codeman.in/something_here/bla/bla/bla/bla.jpg';

preg_replace($pattern, $replaceWith , $string);

Here what is $1 and $3 in the place of replacement string.

output : http://somedomain.com/bla/bla/bla/bla.jpg

  • PHP
  • preg-replace

1 Answers

$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, $2would be the second, etc.

$1 is a reference to whatever is matched by the first (https?:\/\/[^\/]+\/)

$2 is a reference to ([^\/]+\/)

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

 

Leave a Ansewer