Search code examples
phpregexreplacepreg-replaceplaceholder

Replace "@@" with "#" only if contained within "{{" and "}}"


I have to replace some characters in a large string based on some rule:

I'll try to give a couple of examples hoping it'll make it more clear than actually trying to explain the rule:

  • {{ @ text @@ text }} should be {{ @ text # text}}

  • @@ text {{ text 123 @ te@@xt @@ text 34@}} should be @@ text {{ text 123 @ te#xt # text 34@}} (if @@ is not between {{ and }} it should get ignored; also, all @@s between {{ and }} should get replaced)

I unsuccessfully tried:

$text = preg_replace("/({{.*)[@]{2}(.*}})/U", '\\1#\\2', $text);

Solution

  • As you can see here, "{" and "}" are reserved characters used for the start/end min/max quantifier. For this reason, you should backslash these characters in your pattern:

    $text = preg_replace("/(\{\{.*)[@]{2}(.*\}\})/U", '\\1#\\2', $text);
    

    This will replace only one occurrence so you have to put your code in a loop like this:

    $text = '@@ text {{ text 123 @ te@@xt @@ text 34@}}';
    do
    {
        $textBefore = $text;
        $text = preg_replace("/(\{\{.*)[@]{2}(.*\}\})/U", '\\1#\\2', $text);
    } while($textBefore != $text);