10

私はこのような文字列を持っています

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

なりたい

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

例は十分に単純で、私が達成したいことを言葉でよりよく説明できるかどうかはわかりません。

私はいくつかの異なるアプローチを試しましたが、どれもうまくいきませんでした。

4

3 に答える 3

9

これは、単純な文字列置換を呼び出す正規表現で実現できます。

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);

私はあなたのブレースを見つけるために単純な貪欲でない正規表現を選びました、しかしあなたはパフォーマンスのためにまたはあなたのニーズに合うようにこれを変えることを選ぶかもしれません。

匿名関数を使用すると、置換をパラメーター化できます。

$find = '@';
$replace = '###';
$output = preg_replace_callback(
    '/{{.+?}}/',
    function($match) use ($find, $replace) {
        return str_replace($find, $replace, $match[0]);
    },
    $input
);

ドキュメント: http: //php.net/manual/en/function.preg-replace-callback.php

于 2012-05-09T21:22:53.740 に答える
2

2つの正規表現でそれを行うことができます。最初のテキストは{{との間のすべてのテキストを選択し}}、2番目のテキストは。に置き換えられ@ます###。2つの正規表現の使用は、次のように実行できます。

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

これで、1番目と2番目の正規表現を作成して、自分で試してみてください。うまくいかない場合は、この質問で質問してください。

于 2012-05-09T20:58:47.017 に答える
2

別の方法は、正規表現を使用すること(\{\{[^}]+?)@([^}]+?\}\})です。中括弧内の複数@のsを一致させるには、数回実行する必要があります。{{}}

<?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;

どの出力:

{{一部のテキスト###その他のテキスト###およびその他のテキスト}}@これは置き換えられません{{ただし、これは次のようになります:###}}

于 2012-05-09T21:49:40.037 に答える