删除括号之间的文本 PHP

2022-08-30 08:39:49

我只是想知道如何在php中删除一组括号和括号本身之间的文本。

例:

农行 (测试1)

我希望它删除(测试1)并且只离开ABC

谢谢


答案 1
$string = "ABC (Test1)";
echo preg_replace("/\([^)]+\)/","",$string); // 'ABC '

preg_replace是基于 perl 的正则表达式替换例程。此脚本的作用是匹配所有出现的左括号,后跟任意数量的字符(不是右括号),然后再次匹配右括号,然后删除它们:

正则表达式细分:

/  - opening delimiter (necessary for regular expressions, can be any character that doesn't appear in the regular expression
\( - Match an opening parenthesis
[^)]+ - Match 1 or more character that is not a closing parenthesis
\) - Match a closing parenthesis
/  - Closing delimiter

答案 2

接受的答案非常适合非嵌套括号。对正则表达式的轻微修改允许它在嵌套括号上工作。

$string = "ABC (Test1(even deeper) yes (this (works) too)) outside (((ins)id)e)";
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string);

推荐