preg_replace() を使用して、PHP で { } の間の文字列の " と ' を \" に置き換えたいと考えています。
そう:
This is "some" {"text" : 'duudu', 'duuue' : "yey" }
次のようにする必要があります。
This is "some" {\"text\" : \"duudu\", \"duuue\" : \"yey\" }
それについてアドバイスをお願いできますか?
preg_replace() を使用して、PHP で { } の間の文字列の " と ' を \" に置き換えたいと考えています。
そう:
This is "some" {"text" : 'duudu', 'duuue' : "yey" }
次のようにする必要があります。
This is "some" {\"text\" : \"duudu\", \"duuue\" : \"yey\" }
それについてアドバイスをお願いできますか?
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"