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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?