如何让正则表达式忽略括号之间的所有内容?

时间:2012-02-09 21:27:52

标签: php regex

考虑以下字符串:

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

如何让正则表达式忽略{和}之间的内容?

2 个答案:

答案 0 :(得分:15)

试试这个

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

here on Regexr

表示匹配否定字符类中未包含的任何内容,但仅当前面没有前面没有右括号时,这是由否定前瞻(?![^{]*})完成的。

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

答案 1 :(得分:4)

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

另见Split string by delimiter, but not if it is escaped