0

我有一组示例用户字符串输入,其中可能有也可能没有 smarty 变量,这些变量 id 喜欢用 {literal}{/literal} 标签转义。

Array
(
    [0] => {$PLEASE}
    [1] => {PLEASE}
    [2] => {{PLEASE}}
    [3] => {{{PLEASE}}}
    [4] => {a{PLEASE}}
    [5] => {a{$PLEASE}}
    [6] => {{$PLEASE}a}
    [7] => {{PLEASE}a}
    [8] => {{{$PLEASE}}}
    [9] => {{{{PLEASE}}}}
)

这是我希望实现的目标。

Array
(
    [0] => {$PLEASE}
    [1] => {literal}{PLEASE}{/literal}
    [2] => {literal}{{PLEASE}}{/literal}
    [3] => {literal}{{{PLEASE}}}{/literal}
    [4] => {literal}{a{PLEASE}{/literal}
    [5] => {literal}{a{/literal}{$PLEASE}{literal}}{/literal}
    [6] => {literal}{{/literal}{$PLEASE}{literal}a}{/literal}
    [7] => {literal}{PLEASE}a}{/literal}
    [8] => {literal}{{{/literal}{$PLEASE}{literal}}}{/literal}
    [9] => {literal}{{{{PLEASE}}}}{/literal}
)

现在我有这个

$data = preg_replace('/{+([^\$])([a-z0-9]*)}+/si', '{literal}{\1\2}{/literal}', $data);

这给了我

Array
(
    [0] => {$PLEASE}
    [1] => {literal}{PLEASE}{/literal}
    [2] => {literal}{PLEASE}{/literal}
    [3] => {literal}{PLEASE}{/literal}
    [4] => {a{literal}{PLEASE}{/literal}
    [5] => {a{$PLEASE}}
    [6] => {{$PLEASE}a}
    [7] => {literal}{PLEASE}{/literal}a}
    [8] => {{{$PLEASE}}}
    [9] => {literal}{PLEASE}{/literal}
)

现在被卡住了很长一段时间,想知道是否有人可以帮助我解决这个问题,或者是否有可能这样做。

4

1 回答 1

0

好的,我敢肯定有一种更优雅的方式,也许是单线,但无论如何,它适用于以下内容:

//Step 1: Replace 'real' smarty variables with an intermediate string
$data1 = preg_replace('/{(\$\w+)}/', "!!!$1!!!", $arr);
//replace start and end curly braces with {literal}:
$data2 = preg_replace('/{(.*)}/', '{literal}{$1}{/literal}', $data);
//Replace all inner smarty variables with their original string:
$data3 = preg_replace('/.!!!(.*)!!!/', '{/literal}$1{literal}', $data2);
//Replace standalone variables with their original string:
$data4 = preg_replace('/^!!!(.*)!!!$/', '{$1}', $data3);

您可以在一个命令中合并步骤 3 和 4

于 2012-12-09T17:37:36.930 回答