php:从字符串中删除括号/内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1336672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php: remove brackets/contents from a string?
提问by stunnaman
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.
它需要能够支持字符串中任意数量的括号对。
回答by James Wheare
This should do the trick:
这应该可以解决问题:
$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.
修剪是在字符串以括号部分开头的情况下,在这种情况下,它后面的空格不会被删除。
回答by Gumbo
Try this:
尝试这个:
preg_replace('/\([^)]*\)|[()]/', '', $str)
回答by Alix Axel
$string = preg_replace('~\(.*?\)~', '', $string);

