dongshuan8722 2017-09-11 12:58
浏览 71
已采纳

使用Regex替换VQMod中出现的所有字符串

I am building an extension for Opencart 2.3.x and I need to replace all occurences of DIR_IMAGE with _DIR_IMAGE , so I came up with this regular expression that works with PHP alone, but not within a VQMod mod:

<operation error="log">
    <search position="replace"><![CDATA[/(.*?)(DIR_IMAGE)(.*?)/g]]></search>
    <add><![CDATA[$1_DIR_IMAGE$3]]></add>
</operation>

This PHP-only does work:

preg_replace('/(.*?)(DIR_IMAGE)(.*?)/g', '$1_DIR_IMAGE$3', $string);

Can anyone point me in the right direction? At this point I assume alternatives to the expression above are appreciated.

  • 写回答

1条回答 默认 最新

  • dongritan5654 2017-09-11 13:08
    关注

    First of all, you need to tell the engine to use a regex with regex=true attribute.

    Another issue is that g is not supported by PHP preg_replace, it replaces all occurrences by default.

    Besides, you do not need the groups because .*? do not restrict the context (a hint: the .*? at the end of the pattern never matches anything, its group value is always an empty string because it is lazy and is not even tried), you may just use

    <search regex="true" position="replace"><![CDATA[/DIR_IMAGE/]]></search>
    <add><![CDATA[_DIR_IMAGE]]></add>
    

    Note that a regex will make more sense if you need to restrict the context where you match DIR_IMAGE. If you need to match DIR_IMAGE that is not already preprended with _ use

    <search regex="true" position="replace"><![CDATA[/(?<!_)DIR_IMAGE/]]></search>
                                                      ^^^^^^
    

    Since you are using a CDATA block, there is no need to entitize < in the negative lookbehind (?<!_) that fails the match if there is _ immediately to the left of the current location.

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

报告相同问题?

悬赏问题

  • ¥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的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: