Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace

preg_replace("/{{(.*?)}}/e","$$1",$rcontent); 

Please explain the statement to me...i cant understand this

like image 780
sowmiya Avatar asked Oct 20 '10 04:10

sowmiya


1 Answers

Consider an example use:

$rcontent = "abc {{foo}} def";
$foo = 'bar';
$rcontent = preg_replace("/{{(.*?)}}/e","$$1",$rcontent); 
echo $rcontent; // prints abc bar def

I'm assuming that you are assigning the value of preg_match back to $rcontent or else it will not make any sense.

Now the regex you are using is {{(.*?)}} which looks for anything (non-greedyly) between {{ and }} and also remembers the matched string because of the parenthesis.
In my case the .*? matches foo.

Next the replacement part is $$1. Now $1 is foo, so $$1 will be $foo which is bar. So the {{foo}} will be replaced by value of $foo which is bar.

If the $$1 is just a type and you meant to use $1 then the regex replaces {{foo}} with foo.

like image 146
codaddict Avatar answered Oct 04 '22 03:10

codaddict