正则表达式多次替换包围的单词

Fit*_*iti 2 php regex twig

 当它被" {%"和" %}"或" {{"和" }}" 包围时,我试图用树枝语法替换所有" ".

例如,在以下字符串中:

<p>{{ myFunction()&nbsp; }}</p>    
<p>&nbsp;</p>    
<p>{{ number|number_format(2, "&nbsp;.&nbsp;", '&nbsp;,&nbsp;')&nbsp;}}</p>    
<p>{% set myVariable = '&nbsp;&nbsp;' %}</p>
Run Code Online (Sandbox Code Playgroud)

我希望将每个" &nbsp;"除掉" " except the "<p>&nbsp;</p>.

我正在做以下事情:

$content = preg_replace('/({[{%].*)(&nbsp;)(.*[}%]})/', '$1 $3', $content);
Run Code Online (Sandbox Code Playgroud)

但它&nbsp在每个括号环境中只替换一次" ".

如何为所有人做到这一点?

Jan*_*Jan 6

\G 你的朋友在这里:

(?:(?:\{{2}|\{%)           # the start 
|
\G(?!\A))                  # or the beginning of the prev match
(?:(?!(?:\}{2}|%\})).)*?\K # do not overrun the closing parentheses
&nbsp;                     # match a &nbsp;
Run Code Online (Sandbox Code Playgroud)

请参阅regex101.com上的演示.


PHP:

<?php

$string = <<<DATA
<p>{{ myFunction()&nbsp; }}</p>    
<p>&nbsp;</p>    
<p>{{ number|number_format(2, "&nbsp;.&nbsp;", '&nbsp;,&nbsp;')&nbsp;}}</p>    
<p>{% set myVariable = '&nbsp;&nbsp;' %}</p>
DATA;

$regex = '~
            (?:(?:\{{2}|\{%)
            |
            \G(?!\A))
            (?:(?!(?:\}{2}|%\})).)*?\K
            &nbsp;
          ~x';
$string = preg_replace($regex, ' ', $string);

?>
Run Code Online (Sandbox Code Playgroud)

可以在ideone.com上找到完整的代码示例.