Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences inside pattern

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.

like image 274
Sorin Buturugeanu Avatar asked May 09 '12 20:05

Sorin Buturugeanu


1 Answers

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

like image 110
cmbuckley Avatar answered Sep 28 '22 01:09

cmbuckley