簡體   English   中英

PHP-如何用正則表達式按條件替換字符串

[英]PHP - How can regex replace a string by condition

我有一個字符串:

{include "abc"}

{literal} 

function xyz() {

       "ok";

   }

{/literal}

{abc}

{123 }

我只想替換{literal}標簽中的所有{{{}}} 結果將是:

{{include "abc"}}

{{literal}}

   function xyz() {

       "ok";

   }

   //... something contain { and }

{{/literal}}

{{abc}}

{123 }}

有人可以幫助我,謝謝

您可以使用以下模式進行操作:

$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')
~

注意:此模式假定{literal}不能嵌套且始終關閉。 如果{literal}可以保持未關閉狀態,則可以強制執行以下默認行為: “未關閉的{literal}被視為處於打開狀態,直到字符串結尾”

為此,您可以將捕獲組更改為([{}]|(*COMMIT)(*F)) 當第一個分支[{}]失敗時,這意味着到達字符串的結尾。 (*COMMIT)動詞在模式失敗后強制正則表達式引擎停止字符串中的所有研究,而(*F)強制其失敗。 因此{literal}之后的所有內容保持不變。

正則表達式:

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

替換字符串:

\1\1

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM