Replace strings differently depending if is enclosed in braces or not.

Posted by peroyomas on Stack Overflow See other posts from Stack Overflow or by peroyomas
Published on 2010-04-26T19:38:38Z Indexed on 2010/04/26 19:43 UTC
Read the original article Hit count: 141

Filed under:
|

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;

© Stack Overflow or respective owner

Related posts about php

Related posts about regex