preg_replace问题删除括号内的所有内容

时间:2014-08-28 12:47:12

标签: php regex preg-replace

在字符串中我正在尝试使用preg_replace删除括号内的所有内容。

我的代码是:

$text = 'i am (really) tired';
$text = preg_replace('#\([A-Z0-9]\)#', '', $text);
echo $text;

但输出是:

我(真的)累了

知道为什么吗?

3 个答案:

答案 0 :(得分:0)

您需要通过将修饰符i添加到模式(?i)或刚刚添加到正则表达式分隔符来打开不区分大小写的模式。此外,您必须在+之后添加[A-Z0-9]以匹配一个或多个字母数字字符,

$text = 'i am (really) tired';
$text = preg_replace('#\([A-Z0-9]+\)#i', '', $text);
echo $text;

答案 1 :(得分:0)

  #\([A-Z0-9a-z]+\)#

应该是这个。我猜。

答案 2 :(得分:0)

没有量词(*+{m,n}),它只匹配一个字符。除此之外,[A-Z]仅匹配大写字母。您还需要指定[a-z]。 (或指定i标志以忽略大小写)

$text = preg_replace('#\([A-Za-z0-9]+\)#', '', $text);