preg_replace()模式可删除php中的括号和内容

问题描述:

我想使用preg_replace()删除包含其内容的方括号,但是由于结尾方括号是结束字符,因此我无法在模式中使用惰性(非贪心),方括号之间的文本始终是随机字符长度,可以包含数字,下划线和连字符。

I want to remove the brackets with its content using preg_replace(), but i am unable to use a lazy(non-greedy) in the pattern since the end bracket is the end character, the text in between the brackets is always a random character length and can contain numbers, underscores, and hyphens.

code-

$array = array(
   "Text i want to keep (txt to remove)",
   "Random txt (some more random txt)",
   "Keep this (remove)",
   "I like bananas  (txt)"
);

$pattern = "@pattern@";
foreach($array as $new_txt){
   $new_outputs .= preg_replace($pattern, '', $new_txt)."\n";
}
echo $new_outputs;

想要的输出-

Text i want to keep
Random txt
Keep this
I like bananas

我不使用正则表达式,也找不到解决我问题的方法。

I do not use regular expressions much and couldn't find anything to solve my problem.

应该使用以下正则表达式:

The following regular expression should do it:

$pattern = '@\(.*?\)@';

。*?是非贪婪的任何东西都匹配。

.*? is a non-greedy match of anything.