我已经做了几年的正则表达,但是遇到了这个问题。
我正在使用像
这样的字符串$text_body = preg_replace("/[^\{].*?(FIRSTNAME|LASTNAME|PHONE|EMAIL).*?[^\}]+/is", "{VARIABLETHISPARTISFINE}", $text_body);
我正在尝试做的是我正在尝试搜索并替换FIRSTNAME的所有实例| LASTNAME | PHONE | EMAIL,ETC无论我想要什么,但我希望它能够特别忽略任何内部的A { } 要么 ( )。
我该怎么做?
答案 0 :(得分:0)
您可以使用已知的SKIP-FAIL trick。如果您没有嵌套括号或大括号,则可以使用
/(
\([^()]*\) # Match (...) like substrings
|
{[^{}]*} # Match {...} like substrings
)
(*SKIP)(*F) # Ignore the texts matched
|
(?:FIRSTNAME|LASTNAME|PHONE|EMAIL)/x
请参阅regex demo
如果要在嵌套的平衡括号和大括号内忽略PHONE
,EMAIL
之类的单词,请使用基于子程序的正则表达式:
/(?:
(\((?>[^()]|(?1))*\)) # Match (..(.)) like substrings
|
({(?>[^{}]|(?2))*}) # Match {{.}..} like substrings
)
(*SKIP)(*F) # Ignore the texts matched
|
(?:FIRSTNAME|LASTNAME|PHONE|EMAIL)/x
这是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;