I am working on a custom minimalist PHP templating engine for use in personal projects, I need to solve how to make some replacements using a regular expression. I have this string:
$string = 'sometext {% {{ var1 }} middletext {{ var2 }} %} moretext {{ varx }} {% {{ var3 }} %}';
I want to replace all variables between {{ }} delimiters with their php equivalent, but only if they are nested inside {% %} delimiters
This is the desired output:
sometext {% $var1 middletext $var2 %} moretext {{ varx }} {% $var3 %}
So far I have tried this:
echo preg_replace('#\{\{\s*(.*?)\s*\}\}#', '\$$1', $string);
I have even tried this Regex with lookaheads:
echo preg_replace('#(?=.*\{%?)\{\{\s*(.*?)\s*\}\}(?=.*%\})(?!=.*\{%.*%\})#', '\$$1', $string);
But, in both cases I get the same output: All variables in the string are replaced irrespective of being inside {% %} delimiters or not (note how $varx is also undesirably replaced), my incorrect output is:
sometext {% $var1 middletext $var2 %} moretext $varx {% $var3 %}
I have solved it and gotten the output I desire by using foreach loops to match {% %} delimiters first and then replace the variables in the string by using arrays in preg_replace(), like this:
the output can be tested here
But … I’m pretty sure theres a simple one-line of preg_replace() regex code that can achieve the same desired output. Any ideas?