考虑以下字符串:
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 :(得分:15)
试试这个
[^a-zA-Z {}]+(?![^{]*})
表示匹配否定字符类中未包含的任何内容,但仅当前面没有前面没有右括号时,这是由否定前瞻(?![^{]*})
完成的。
$string preg_replace('/[^a-zA-Z {}]+(?![^{]*})/', '', $string);
答案 1 :(得分:4)
$str = preg_replace('(\{[^}]+\}(*SKIP)(*FAIL)|[^a-zA-Z ]+)', '', $str);