当它被" {%"和" %}"或" {{"和" }}" 包围时,我试图用树枝语法替换所有" ".
例如,在以下字符串中:
<p>{{ myFunction() }}</p>
<p> </p>
<p>{{ number|number_format(2, " . ", ' , ') }}</p>
<p>{% set myVariable = ' ' %}</p>
Run Code Online (Sandbox Code Playgroud)
我希望将每个" "除掉" " except the "<p> </p>.
我正在做以下事情:
$content = preg_replace('/({[{%].*)( )(.*[}%]})/', '$1 $3', $content);
Run Code Online (Sandbox Code Playgroud)
但它 在每个括号环境中只替换一次" ".
如何为所有人做到这一点?
\G 你的朋友在这里:
(?:(?:\{{2}|\{%) # the start
|
\G(?!\A)) # or the beginning of the prev match
(?:(?!(?:\}{2}|%\})).)*?\K # do not overrun the closing parentheses
# match a
Run Code Online (Sandbox Code Playgroud)
请参阅regex101.com上的演示.
PHP:
<?php
$string = <<<DATA
<p>{{ myFunction() }}</p>
<p> </p>
<p>{{ number|number_format(2, " . ", ' , ') }}</p>
<p>{% set myVariable = ' ' %}</p>
DATA;
$regex = '~
(?:(?:\{{2}|\{%)
|
\G(?!\A))
(?:(?!(?:\}{2}|%\})).)*?\K
~x';
$string = preg_replace($regex, ' ', $string);
?>
Run Code Online (Sandbox Code Playgroud)
可以在ideone.com上找到完整的代码示例.
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |