【发布时间】:2014-08-28 12:47:12
【问题描述】:
在字符串中,我尝试使用 preg_replace 删除括号内的所有内容。
我的代码是:
$text = 'i am (really) tired';
$text = preg_replace('#\([A-Z0-9]\)#', '', $text);
echo $text;
但输出是:
我(真的)很累
知道为什么吗?
【问题讨论】:
标签: php regex preg-replace
在字符串中,我尝试使用 preg_replace 删除括号内的所有内容。
我的代码是:
$text = 'i am (really) tired';
$text = preg_replace('#\([A-Z0-9]\)#', '', $text);
echo $text;
但输出是:
我(真的)很累
知道为什么吗?
【问题讨论】:
标签: php regex preg-replace
您需要通过将修饰符 i 添加到您的模式 (?i) 或在正则表达式分隔符之后来打开不区分大小写的模式。而且你必须在[A-Z0-9] 之后添加+ 以匹配一个或多个字母数字字符,
$text = 'i am (really) tired';
$text = preg_replace('#\([A-Z0-9]+\)#i', '', $text);
echo $text;
【讨论】:
#\([A-Z0-9a-z]+\)#
应该是这个。我猜。
【讨论】:
如果没有量词(*、+ 或 {m,n}),它只会匹配单个字符。除此之外,[A-Z] 仅匹配大写字母。您还需要指定[a-z]。 (或指定i 标志以忽略大小写)
$text = preg_replace('#\([A-Za-z0-9]+\)#', '', $text);
【讨论】: