Replace all occurrences within the template

I have a line that looks like this

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

I want him to become

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

I think that the example is fairly straightforward, and I'm not sure that I’ll better explain what I want to achieve with words.

I tried several different approaches, but no one worked.

+8
php regex preg-replace pcre
source share
3 answers

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

+8
source share

You can do this with 2 regular expressions. The first selects all text between {{ and }} , and the second replaces @ with ### . Using 2 regular expressions can be done as follows:

 $str = preg_replace_callback('/first regex/', function($match) { return preg_replace('/second regex/', '###', $match[1]); }); 

Now you can create the first and second regular expressions, try it yourself, and if you do not get it, ask it in this question.

+2
source share

Another method would be to use the regular expression (\{\{[^}]+?)@([^}]+?\}\}) . You will need to execute it several times to match multiple @ inside {{ brackets }} :

 <?php $string = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}'; $replacement = '#'; $pattern = '/(\{\{[^}]+?)@([^}]+?\}\})/'; while (preg_match($pattern, $string)) { $string = preg_replace($pattern, "$1$replacement$2", $string); } echo $string; 

What outputs:

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

+2
source share

All Articles