我想用preg_replace()替换PHP中{}之间的字符串中的"和' for '"。
:
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"