简体   繁体   English

PHP正则表达式不起作用 - 解析{{tags}}

[英]PHP regular expression not working - parsing {{tags}}

What I want to do it parse the following string in a way that all placeholders inside {{}} are replace by the value indicated by "default". 我想要做的是解析以下字符串,使{{}}内的所有占位符都被“default”指示的值替换。 For instance, {{time, default=noon}} should become noon . 例如, {{time, default=noon}}应该成为noon

Here's the code I tried: 这是我试过的代码:

$input = 'It was a {{color, default=black}} and scary {{phase}}. As the {{animals, default=dogs}} {{make_sound, default=barked}} and the trees swayed {{setting, default=to the breeze}}, a {{size, default=}} {{monster, default=troll}} that emerged from the shadows.';
$input = preg_replace('/\{\{.*default=(\w+)\}\}/i', '$1', $input);
echo $input;

The output produced is: Output: It was a troll that emerged from the shadows. 产生的输出是: Output: It was a troll that emerged from the shadows.

Why are the remaining patterns not getting parsed correctly? 为什么剩余的模式无法正确解析?

{{[^}]*\bdefault=([^}]*)}}

You can try this.Replace by $1 .See demo. 你可以试试这个。放置$1 。看看演示。

https://regex101.com/r/aG0sF5/4 https://regex101.com/r/aG0sF5/4

Because .* is greedy. 因为.*很贪心。 And also a non-greedy regex .*? 还有一个非贪婪的正则表达式.*? won't work here because .*? 不会在这里工作,因为.*? will also match }} . 也将匹配}}

preg_replace('/\{\{(?:(?!\}\}).)*?default=(.*?)\}\}/i', '\1', $input);

DEMO DEMO

please see the Demo 请看演示

=(.*?)}

正则表达式可视化

Debuggex Demo Debuggex演示

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

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