[英]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.
为什么剩余的模式无法正确解析?
因为.*
很贪心。 还有一个非贪婪的正则表达式.*?
不会在这里工作,因为.*?
也将匹配}}
。
preg_replace('/\{\{(?:(?!\}\}).)*?default=(.*?)\}\}/i', '\1', $input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.