Replace all occurrences inside pattern
Solution 1
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
Solution 2
Another method would be to use the regex (\{\{[^}]+?)@([^}]+?\}\})
. You'd need to run over it a few times to match multiple @
s inside {{
braces }}
:
<?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;
Which outputs:
{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }}
Solution 3
You can do it with 2 regexes. The first one selects all text between {{
and }}
and the second replaced @
with ###
. Using 2 regexes can be done like this:
$str = preg_replace_callback('/first regex/', function($match) {
return preg_replace('/second regex/', '###', $match[1]);
});
Now you can make the first and second regex, try yourself and if you don't get it, ask it in this question.
Sorin Buturugeanu
Updated on July 19, 2022Comments
-
Sorin Buturugeanu almost 2 years
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.
-
melvin over 5 yearswill preg_replace inside preg_replace_callback affects performace since finding a string twice ?