简体   繁体   English

PHP preg_replace

[英]PHP preg_replace

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

请向我解释声明......我无法理解这一点

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. 我假设您将preg_match的值分配回$rcontent ,否则它将没有任何意义。

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 . 匹配foo

Next the replacement part is $$1 . 接下来更换零件是$$1 Now $1 is foo , so $$1 will be $foo which is bar . 现在$1foo ,所以$$1将是$foo ,这是bar So the {{foo}} will be replaced by value of $foo which is bar . 所以{{foo}}将被$foo的值替换为bar

If the $$1 is just a type and you meant to use $1 then the regex replaces {{foo}} with foo . 如果$$1仅仅是一个类型,你想用$1 ,则正则表达式替换{{foo}}foo

lazy * Repeats the previous item zero or more times. lazy *重复前一项零次或多次。 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 abc "def" "ghi" jkl匹配"def"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM