PHP的:从字符串中删除括号/内容?
问题描述:
如果我有这样的字符串:
If I have a string like this:
$str = "blah blah blah (a) (b) blah blah blah";
如何进行正则表达式,以便输出为:
How can I regex so that the output is:
$str = "blah blah blah blah blah blah";
它需要能够在字符串中支持任意数量的括号对.
It needs to be able to support any number of bracket pairs inside a string.
答
这应该可以解决问题:
$str = trim(preg_replace('/\s*\([^)]*\)/', '', $str));
请注意,与其他建议不同,此答案也消除了括号内的空白.
Note, this answer removes whitespace around the bracket too, unlike the other suggestions.
修剪是为了防止字符串以方括号开头,在这种情况下,不会删除其后的空白.
The trim is in case the string starts with a bracketed section, in which case the whitespace following it isn't removed.