- preg_replace: documentation ( source)
<?php
$input = <<<STR
<p>{{ myFunction() }}</p>
<p> </p>
<p>{{ number|number_format(2, " . ", ' , ') }}</p>
<p>{% set myVariable = ' ' %}</p>
STR;
echo preg_replace('/ (?=(?:(?!{[{%]).)*[%}]})/', ' ', $input);