Replace all occurrences inside pattern

Sorin Buturugeanu picture Sorin Buturugeanu · May 9, 2012 · Viewed 18.8k times · Source

I have a string that is like this

{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}

I want it to become

{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }}

I guess the example is straight forward enough and I'm not sure I can better explain what I want to to achieve in words.

I tried several different approaches but none worked.

Answer

cmbuckley picture cmbuckley · May 9, 2012

This can be achieved with a regular expression calling back to a simple string replace:

function replaceInsideBraces($match) {
    return str_replace('@', '###', $match[0]);
}

$input = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}';
$output = preg_replace_callback('/{{.+?}}/', 'replaceInsideBraces', $input);
var_dump($output);

I have opted for a simple non-greedy regular expression to find your braces but you may choose to alter this for performance or to suit your needs.

Anonymous functions would allow you to parameterise your replacements:

$find = '@';
$replace = '###';
$output = preg_replace_callback(
    '/{{.+?}}/',
    function($match) use ($find, $replace) {
        return str_replace($find, $replace, $match[0]);
    },
    $input
);

Documentation: http://php.net/manual/en/function.preg-replace-callback.php