Search code examples
phpregexstringreplaceplaceholder

Replace backslash-prefixed placeholders according to placeholder attributes


$string= 'This is example string \add[name1]{added} and \remove[name2]{removed text}  \change[name1]{this}{to}.'`

Here \add[name1]{added} should be replaced to added (\add = string is added)

\remove[name2]{removed text} should be replaced to empty text ( removed text is removed)

\change[name1]{this}{to} should be replaced to this (here \change means to is changed to this)

Expected outputThis is example string added and this.

I tried regex for this,

preg_match('/\\add\[name1]{(.*?)}/',$string,$match) //for add (\add)
str_replace($match[0],$match[1],$match[0])
//problem is [name] is not constant so how to get the string between
//"\add[anything]{" and "}" I will apply same regex for this
//"\remove[anything]{" and "}" too.

For \change[anything]{string1}{string2}should be replaced to string1


Solution

  • You can do this with back references, e.g. $1. Just remember to escape your backslashes twice, once for PHP and once for the RegEx:

    <?php
    $string= 'This is example string '
        . '\add[name1]{added} '
        . 'and '
        . '\remove[name2]{removed text}'
        . '\change[name1]{this}{to}.';
    
    //$string = preg_replace('#\\add\[.*?\]\{(.*?)\}#', '$1', $string);
    
    // Apply add
    $string = preg_replace('/\\\\add\\[.*?\\]\\{(.*?)\\}/', '$1', $string);
    
    // Apply change
    $string = preg_replace('/\\\\change\\[.*?\\]\\{(.*?)\\}\\{.*?\\}/', '$1', $string);
    
    // Apply remove
    $string = preg_replace('/\\\\remove\\[.*?\\]\\{(.*?)\\}/', '', $string);
    
    echo $string, PHP_EOL;
    

    Output:

    This is example string added and this.