This can be achieved with a regex returning to a simple string replacement:
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 chose a simple, non-greedy regex to find curly braces, but you can change this for performance or to suit your needs.
Anonymous functions allow you to parameterize 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
cmbuckley
source share