2012-02-09 119 views
8

考慮以下字符串:如何讓正則表達式忽略括號內的所有內容?

I have been driving to {Palm.!.Beach:100} and it . was . great!! 

我用下面的正則表達式來刪除所有標點符號:

$string preg_replace('/[^a-zA-Z ]+/', '', $string); 

此輸出:

I have been driving to PalmBeach and it was great!! 

但我需要的正則表達式來總是忽略任何介於{和}之間。因此,所需的輸出將是:

I have been driving to {Palm.!.Beach:100} and it was great 

我怎樣才能讓正則表達式忽略之間是什麼{和}?

+0

的可能的複製[小寫的一切,除了當括號(http://stackoverflow.com/questions/9229030/lowercase-everything-except-when-between-brackets) – hakre 2012-02-13 13:22:44

回答

11

試試這個

[^a-zA-Z {}]+(?![^{]*}) 

看到它here on Regexr

表示匹配不包含在否定字符類的東西,但前提是前面沒有右括號不前的開放,這樣做由負向預測(?![^{]*})

$string preg_replace('/[^a-zA-Z {}]+(?![^{]*})/', '', $string); 
+0

我的錯誤 - 我忘記了所有不在括號之間的東西都應該返回小寫。所以,再次,括號之間的內容是孤立的。這個正則表達式能否以小寫字母返回其餘部分? – Pr0no 2012-02-10 00:23:51

+0

我會說,不在同一preg_replace。但在第二步中沒有問題。檢查這[鏈接](http://de2.php.net/manual/en/functions.anonymous.php)它應該讓你開始。如果你有問題,那麼請問一個新問題。 – stema 2012-02-10 07:05:52

4
$str = preg_replace('(\{[^}]+\}(*SKIP)(*FAIL)|[^a-zA-Z ]+)', '', $str); 

另請參閱Split string by delimiter, but not if it is escaped

+0

我來到了幾分[相似結論](http://stackoverflow.com/a/9260679/367456)(根據你的鏈接的答案;))在一個(如我現在看到)重複的問題。 – hakre 2012-02-13 13:20:32

+0

Yay,+100 for'(* SKIP)(* F)'!... @Pr0no這是一個非常有用和有趣的技術,[this](http://stackoverflow.com/q/23589174/)解釋它詳細。 :) – zx81 2014-06-25 23:51:20

相關問題