0

preg_replace() を使用して、PHP で { } の間の文字列の " と ' を \" に置き換えたいと考えています。

そう:

This is "some" {"text" : 'duudu', 'duuue' : "yey" }

次のようにする必要があります。

This is "some" {\"text\" : \"duudu\", \"duuue\" : \"yey\" }

それについてアドバイスをお願いできますか?

4

1 に答える 1

1

preg_replace_callback を使用してこの問題を解決できます。次のコードを検討してください。

$str = 'This is "some" {"text" : \'duudu\', \'duuue\' : "yey" } "and" {"some", "other"} "text"';
echo preg_replace_callback('~({[^}]*})~', function($m) {
       return preg_replace('~(?<!\\\\)[\'"]~', '\"', $m[1]);
    }, $str) . "\n";

更新:純粋な正規表現ベースのソリューションが好きな純粋主義者向け:

$repl= preg_replace('~(?<!\\\\) [\'"] (?! (?: [^{}]*{ [^{}]*} ) * [^{}]* $)~x',
                    '\"' , $str);

出力:

This is "some" {\"text\" : \"duudu\", \"duuue\" : \"yey\" } "and" {\"some\", \"other\"} "text"


ライブデモ: http://ideone.com/PfGzxd

于 2013-04-16T13:39:13.557 に答える