将双大括号占位符替换为与占位符文本匹配的变量值

发布于 2024-09-27 21:22:02 字数 90 浏览 0 评论 0原文

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

请向我解释一下该声明。

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

Please explain the statement to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

难理解 2024-10-04 21:22:02

考虑一个示例使用:

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

我假设您将 preg_match 的值分配回 $rcontent,否则它将没有任何意义。

现在您使用的正则表达式是 {{(.*?)}} ,它会查找 {{}} 并会因为括号而记住匹配的字符串。
在我的例子中,.*?foo 匹配。

接下来的替换部件是$$1。现在 $1foo,因此 $$1 将是 $foo,即 bar 。因此,{{foo}} 将被替换为 $foo 的值,即 bar

如果 $$1 只是一种类型,并且您打算使用 $1,则正则表达式会将 {{foo}} 替换为 foo< /代码>。

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.

め七分饶幸 2024-10-04 21:22:02

懒惰的 *
重复前一项零次或多次。惰性,因此引擎首先尝试跳过前一项,然后再尝试对前一项不断增加的匹配进行排列。

例如: .*? 匹配 abc "def" "ghi" jkl 中的 "def"

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文