PHP regex not working - parsing {{tags}}
What I want to do is parse the next line in such a way that all placeholders inside {{}}
are replaced with the value denoted by "default". For example, it {{time, default=noon}}
should become noon
.
Here is 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;
Output Output: Output: It was a troll that emerged from the shadows.
Why are the remaining templates not processing correctly?
{{[^}]*\bdefault=([^}]*)}}
You can try this.Replace by. $1
View demo.
https://regex101.com/r/aG0sF5/4
Because he is .*
greedy. And also a non-greedy regex .*?
won't work here because it .*?
will match as well }}
.
preg_replace('/\{\{(?:(?!\}\}).)*?default=(.*?)\}\}/i', '\1', $input);
DEMO
see demo
=(.*?)}
Demo Debuggex