【发布时间】:2015-05-29 06:08:05
【问题描述】:
我想要做的是解析以下字符串,将{{}} 中的所有占位符替换为“默认”指示的值。例如,{{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.
为什么没有正确解析剩余的模式?
【问题讨论】:
-
因为 .* 是贪婪的。
-
{{phase}}会发生什么 -
@AvinashRaj 好点!我把 * 换成了 *?并且结果有所改善。不过仍然不完美。
-
@vks 因为任务是更大问题的一部分,所以它悄悄出现了。请暂时忽略它。 :-)
-
@dotslash 你的预期输出是什么?