Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-正则表达式如何按条件替换字符串_Php_Regex_Replace_Conditional Statements - Fatal编程技术网

PHP-正则表达式如何按条件替换字符串

PHP-正则表达式如何按条件替换字符串,php,regex,replace,conditional-statements,Php,Regex,Replace,Conditional Statements,我有一个字符串: {include "abc"} {literal} function xyz() { "ok"; } {/literal} {abc} {123 } 我只想将所有{替换为{{和}替换为}而不是{literal}标记。结果将是: {{include "abc"}} {{literal}} function xyz() { "ok"; } //... something contain { and }

我有一个字符串:

{include "abc"}

{literal} 

function xyz() {

       "ok";

   }

{/literal}

{abc}

{123 }
我只想将所有
{
替换为
{{
}
替换为
}
而不是
{literal}
标记。结果将是:

{{include "abc"}}

{{literal}}

   function xyz() {

       "ok";

   }

   //... something contain { and }

{{/literal}}

{{abc}}

{123 }}
有人可以帮我,谢谢

(?s)(?<=\{literal\}).*?(?=\{\/literal\})(*SKIP)(*F)|([{}])

您可以使用以下模式:

$pattern = '~(?:(?<={literal})[^{]*(?:{(?!/literal})[^{]*)*+|[^{}]*)([{}])\K~'

$text = preg_replace($pattern, '$1', $text);

$pattern='~(?:(?你试过什么吗?是我一个人,还是这是另一个X-Y问题?你为什么要求助于正则表达式来解决这个问题?我觉得你好像在试图解析一些东西哦,我试着解析smarty:)非常感谢你,这对我来说很有用。我想你是正则表达式的大师:D
$pattern = '~(?:(?<={literal})[^{]*(?:{(?!/literal})[^{]*)*+|[^{}]*)([{}])\K~'

$text = preg_replace($pattern, '$1', $text);
~                       # pattern delimiter
(?:                     # non-capturing group
    (?<={literal})      # lookbehind: preceded by "{literal}"
                        # a lookbehind doesn't capture any thing, it is only a test
    [^{]*               # all that is not a {
    (?:
        {(?!/literal})  #/# a { not followed by "/literal}"
        [^{]*
    )*+                 # repeat as needed
  |                     # OR
    [^{}]*              # all that is not a curly bracket,
                        # (to quickly reach the next curly bracket)
)
([{}])                  # capture a { or a } in group 1
\K                      # discards all on the left from match result
                        # (so the whole match is empty and nothing is replaced,
                        # the content of the capture group is only added 
                        # with the replacement string '$1')
~