Replace strings differently depending if is enclosed in braces or not.
- by peroyomas
I want to replace all instances of an specific words between braces with something else, unless it is written between double braces, while it should show as is it was written with single braces without the filter.
I have tried a code but only works for the first match. The rest are shown depending of the first one:
$foo = 'a {bar} b {{bar}} c {bar} d';
$baz = 'Chile';
preg_match_all( '/(\{?)\{(tin)\}(\}?)/i', $foo, $matches, PREG_SET_ORDER );
if ( !empty($matches) ) {
foreach ( (array) $matches as $match ) {
if( empty($match[1]) && empty($match[3])) {
$tull = str_replace( $match[0], $baz, $foo );
} else {
$tull = str_replace( $match[0], substr($match[0], 1, -1), $foo ) ;
}
}
}
echo $tull;