Farklı parantez içinde veya kapalı olup olmadığını bağlı dizeleri yerine

2 Cevap php

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;

EDIT: çantası kullanın:

Ben yazarsanız:

"Çıkışına Yaz {{}} çubuğu şablonu Örnek:. I {} bara gitmek istiyorum."

Ben istiyorum:

". Çıkış şablon Örnek {bar} yazın: Ben ŞİLİ gitmek istiyorum."

2 Cevap

Sen tek hazırladı olanlar için çift hazırladı öğeler ve başka bakmak için iki normal ifadeler, birini kullanabilirsiniz. Alternatif olarak, bir geri arama sadece bir düzenli ifade ile değiştirme değerini belirlemek için kullanılan olabilir.

Separate patterns

$subject = 'Write {{bar}} to output the template. Example: I want to go to {bar}.';
$replacement = 'CHILE';
echo preg_replace(
    array('/(?<!\{)\{bar\}(?!\})/', '/\{\{bar\}\}/'),
    array($replacement, '{bar}'),
    $subject
);

Single pattern with callback

echo preg_replace_callback(
    '/(\{)?(\{bar\})(?(1)\})/',
    function ($match) use ($replacement) {
        if ($match[0][1] === '{') {
            return $match[2];
        }
        return $replacement;
    },
    $subject
);

Son olarak, (her zaman bar) veya etiket kısmı bazı değişen değiştirme dizesi için bir anahtar olacak bir sabit kodlu etiketler için yapıyorsun?

Tek bir regex bunu yapamazsınız. İlk kullanım

(?<!\{)\{bar\}(?!\})

etrafında başka parantez vardır {bar} sadece eşleşecek. Yani

preg_replace('/(?<!\{)\{bar\}(?!\})/m', 'CHILE', 'Write {{bar}} to output the template. Example: I want to go to {bar}.');

döndürür

Write {{bar}} to output the template. Example: I want to go to CHILE.

Sonra yapmak normal bir ile {{ { ve }} ile değiştirin arama ve değiştirme }.