【问题标题】:preg_replace issue with delete everything inside parenthesis [duplicate]preg_replace 删除括号内所有内容的问题[重复]
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
        #\([A-Z0-9a-z]+\)#
      

      应该是这个。我猜。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2022-11-03
          • 2013-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-06
          • 1970-01-01
          相关资源
          最近更新 更多