Search code examples
phpregexvqmodopencart2.3

Using Regex replace all occurences of string within 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.


Solution

  • 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.