开发者

PHP preg_replace

开发者 https://www.devze.com 2023-01-21 15:28 出处:网络
preg_replace(\"/{{(.*?)}}/e\",\"$$1\",$rcontent); Please explain the statement to me...i cant unde开发者_开发问答rstand thisConsider an example use:
preg_replace("/{{(.*?)}}/e","$$1",$rcontent); 

Please explain the statement to me...i cant unde开发者_开发问答rstand this


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.


lazy * Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item.

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号