dongzenglin8292 2012-03-11 14:45
浏览 22
已采纳

php正则表达式删除文本

If I have a string of the form:

$text='remove1  (keep1) remove2 (keep2) remove3';

Using the response

https://stackoverflow.com/a/5293343/1154853

$re = '/[^()]*+(\((?:[^()]++|(?1))*\))[^()]*+/';
$text = preg_replace($re, '$1', $text);

I get

(keep1)(keep2)

If I want to go from

$text='remove1  {keep1} remove2 {keep2} remove3';

to

{keep1}{keep2}

that is I want to change the delimiters, how do I change the given regular expression? I tried all sorts of combinations of changing ( to { but I couldn't get it to work. I find these reg exp pretty tough!

  • 写回答

3条回答 默认 最新

  • douka19950505 2012-03-11 14:51
    关注

    For parentheses (), you could use:

    $re = '/(?:^|(?<=\)))[^(]+/';
    $text = preg_replace($re, '', $text);
    

    EDIT For braces {}, use this variant:

    $re = '/(?:^|(?<=\}))[^{]+/';
    $text = preg_replace($re, '', $text);
    

    Note that these will fail - as all regex does - for nested structures.

    Explanation

    (?:        # non-capturing group start
      ^        #   start-of-string
      |        #   or...
      (?<=\})  #   look-behind: a position preceded by a } closing brace
    )          # end non-capturing group
    [^{]+      # any character except an opening brace, multiple times
    

    The non-capturing group fixes the start of the match behind a closing brace or at the start of the string. The [^{]+ matches every character up to the next brace. Effectively this matches everything in-between {words}.

    See it: http://rubular.com/r/1Sp72TbHIi

    EDIT #2 Of course, thinking less complicated, this would also work:

    $re = '/((?:\\\w+)?\{[^}]*\})/';
    $text = preg_replace($re, '$1', $text);
    

    http://rubular.com/r/rPLMbCLbcq

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算