2015-10-17 223 views
1

我目前使用正則表達式從字符串中刪除括號。它運行良好,甚至可以應用於嵌套括號。但是,有時候我不想刪除括號及其內容。如何刪除包含單詞remove.的括號(及其內容)並保留其他括號?刪除包含某個單詞的括號 - 正則表達式

$string = "ABC (test. blah blah) outside (remove. take out)"; 
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string); 

回答

1

試試這個正則表達式:

[(](?![^)]*?remove)([^)]+)[)] 

而且通過$1更換。

Regex live here.

解釋:

[(]   # the initial '(' 
(?!   # don't match if in sequence is found: 
    [^)]*?  # before the closing ')' 
    remove  # the 'remove' text 
)    # 
([^)]+)  # then, save/group everything till the closing ')' 
[)]   # and the closing ')' itself 

希望它能幫助。


或者簡單:

[(](?=[^)]*?remove)([^)]+)[)] 

要匹配那些有remove文本。看起來=而不是!

Regex live here.


隨着php代碼,它應該是:

$input = "ABC (test. blah blah) outside (remove. take out)"; 
ECHO preg_replace("/[(](?=[^)]*?remove)([^)]+)[)]/", "$1", $input); 

希望它能幫助。

+0

不確定你的意思是「用$ 1替換」你能用php代碼修改嗎?謝謝。 – MaryCoding

+0

完美。有兩個刪除額外的空間嗎?格式化後,它留下雙空格 – MaryCoding

+0

@MaryCoding。是的,只需在正則表達式的末尾添加'\ s?'。 – 2015-10-17 00:31:11

相關問題