替换时使用正则表达式但在 {} 标记或括号内忽略

Regex while Replacing but IGNORE Within { } tags or inside Parentheses

几年来我一直在做正则表达式,但在这个方面遇到了麻烦。

我使用的字符串类似于

$text_body = preg_replace("/[^\{].*?(FIRSTNAME|LASTNAME|PHONE|EMAIL).*?[^\}]+/is", "{VARIABLETHISPARTISFINE}", $text_body);

我想做的是让它搜索并替换 FIRSTNAME|LASTNAME|PHONE|EMAIL 等的所有实例,无论我想要什么,但我希望它特别忽略{ } 或 ( ) 内的任何内容。

请问我该怎么做?

您可以使用已知的SKIP-FAIL trick。如果你没有嵌套的圆括号或大括号,你可以使用

/(
  \([^()]*\) # Match (...) like substrings
 |
  {[^{}]*}   # Match {...} like substrings
)
(*SKIP)(*F)  # Ignore the texts matched
|
(?:FIRSTNAME|LASTNAME|PHONE|EMAIL)/x

regex demo

如果您想忽略嵌套平衡圆括号和大括号内的 PHONEEMAIL 等词,请使用基于子例程的正则表达式:

/(?:
 (\((?>[^()]|(?1))*\)) # Match (..(.)) like substrings
 |
 ({(?>[^{}]|(?2))*})   # Match {{.}..} like substrings
)
(*SKIP)(*F)  # Ignore the texts matched
|
(?:FIRSTNAME|LASTNAME|PHONE|EMAIL)/x

another regex demo

这是一个IDEONE demo:

$re = "/(?:
 (\((?>[^()]|(?1))*\)) # Match (..(.)) like substrings
 |
 ({(?>[^{}]|(?2))*})   # Match {{.}..} like substrings
)
(*SKIP)(*F)  # Ignore the texts matched
|
(?:FIRSTNAME|LASTNAME|PHONE|EMAIL)/x"; 
$str = "FIRSTNAME LASTNAME PHONE EMAIL {FIRSTNAME LASTNAME PHONE EMAIL{FIRSTNAME LASTNAME PHONE EMAIL }FIRSTNAME LASTNAME PHONE EMAIL }"; 
$n = preg_replace($re, "", $str);
echo $n;