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


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

我已经做了几年的正则表达式了,但遇到了麻烦。

我正在使用这样的字符串

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

我想做的是我试图让它搜索并替换 FIRSTNAME| 的所有实例|姓氏|电话|电子邮件等 无论我想要什么,但我希望它特别忽略 { } 或 ( ) 中的任何内容。

请问我该怎么做?

您可以使用已知的 SKIP-FAIL 技巧。如果没有嵌套的括号和大括号,则可以使用

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

查看正则表达式演示

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

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

查看另一个正则表达式演示

下面是一个 IDEONE 演示:

$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;
相关文章: