dongru3726 2016-07-20 13:24
浏览 45
已采纳

正则表达式PHP查找字符串并删除父级

in a very big string I have to delete the [w:r][/w:r] where the substring "delete" exist. Example -of substring I want to delete - :

[w:r w:rsidR="00A37EED" w:rsidRPr="00FE1BE1"][w:rPr][w:b][/w:rPr][w:t]delete[/w:t][/w:r]

This one is my best guess \[w:r.*delete.*\[\/w:r\] I tried multiple regex expression but it's not my strong suit.

I copy-pasted the string on regex101 here's the link https://regex101.com/r/wS4bL2/1

I succeeded at finding the required pattern but I can't make it stop at the first occurence of [/w:r].

PHP code -in case you are wondering- :

$this->tempDocumentMainPart = preg_replace('/\[w:r.*delete.*\[\/w:r\]/','',$this->tempDocumentMainPart);
  • 写回答

1条回答 默认 最新

  • douraoyw194498 2016-07-20 13:32
    关注

    The .* will overflow across the [....]s. One way is to use a tempered greedy token:

    \[w:r\b(?:(?!\[w:r\b).)*?delete(?:(?!\[w:r\b).)*?\[\/w:r]
            ^^^^^^^^^^^^^^^^^       ^^^^^^^^^^^^^^^^^
    

    See the regex demo

    The (?:(?!\[w:r\b).)*? tempered greedy token will limit matching inside one [w:r (that has a word boundary on the right).

    Add a DOTALL modifier /s ('/PATTERN/s') so as to match across newlines.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: