Php 替换括号之间的撇号

Php 替换括号之间的撇号,php,Php,我想用preg_replace()替换PHP中介于{}之间的字符串中的“and'for\” 因此: 应该是: This is "some" {\"text\" : \"duudu\", \"duuue\" : \"yey\" } 您能提供一些建议吗?您可以使用preg\u replace\u callback来解决此问题。考虑下面的代码: $str = 'This is "some" {"text" : \'duudu\', \'duuue\' : "yey" } "and" {"some",

我想用preg_replace()替换PHP中介于{}之间的字符串中的“and'for\”

因此:

应该是:

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

您能提供一些建议吗?

您可以使用preg\u replace\u 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";


现场演示:请展示您尝试过的内容,堆栈溢出不是免费的代码服务;-)<如果可以嵌套大括号,则code>preg_replace()无法检测是否有东西在{}之间。即使是像
{“oo”:“o{o”}
这样的情况也不能由
preg_replace()
来处理。如果您试图创建JSON代码,PHP有一个内置函数来实现这一点
JSON_encode()
。不要尝试手动创建json字符串;这将导致错误和安全漏洞。我正在编写使用动态参数(有时是json)的解析器脚本。因为最终用户可以调用嵌入HTML的函数-“some”例如,是第一个函数参数,json代码是第二个。从DB的角度来看,一切都很好,但在执行eval时出错。另一个解决方案:
explode()
by
{
一次(参见第三个参数),然后在数组中有两个结果。左侧的结果保留,右侧的结果按
}
一次,你又得到了两个结果,左边是
{}
中的字符串,所以
str\u replace
所有
\”
。重新开始右边的结果(如果可能有多个
{…}
块)。你可以递归地这样做。
$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"