繁体   English   中英

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

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

我想要做的是解析以下字符串,使{{}}内的所有占位符都被“default”指示的值替换。 例如, {{time, default=noon}}应该成为noon

这是我试过的代码:

$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;

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

为什么剩余的模式无法正确解析?

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

你可以试试这个。放置$1 。看看演示。

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

因为.*很贪心。 还有一个非贪婪的正则表达式.*? 不会在这里工作,因为.*? 也将匹配}}

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

DEMO

请看演示

=(.*?)}

正则表达式可视化

Debuggex演示

暂无
暂无

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

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