PHP preg_replace

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

Please explain this expression to me ... I cannot understand it.

+6
php regex preg-replace
source share
2 answers

Consider a usage example:

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

I assume that you assign the value of preg_match back to $rcontent , otherwise it will not make any sense.

Now the regular expression used is {{(.*?)}} , Which searches for something (not greedily) between {{ and }} , and also remembers the line with the match because of the bracket.
In my case .*? matches foo .

Next is the spare part $$1 . Now $1 is foo , so $$1 will be $foo , which is equal to bar . Thus, the value {{foo}} will be replaced by the value of $foo , which is equal to bar .

If $$1 is just a type and you wanted to use $1 , then the regular expression replaces {{foo}} with foo .

+4
source share

lazy * Repeats the previous item zero or more times. Lazy, therefore, the engine first tries to skip the previous element before attempting permutations with ever-increasing matches of the previous element.

for example:. .*? matches "def" in abc "def" "ghi" jkl

http://www.regular-expressions.info/reference.html

0
source share

All Articles