将“替换为 ”,但仅当用“.


Replace " with ", only if enclosed by "

我正在从数据库中读取一个字符串,json_encode不起作用。(使用PHP)

我需要用 '" 替换所有出现的 " ,但前提是该出现已经包含在 " 中。

示例字符串:

{"val1": "This is "some value" that is inside of the "string" and such", "val2": "And here is yet another "value" that is messed up by quotation marks", "val3": "etc. etc."}

应改为:

{"val1": "This is '"some value'" that is inside of the '"string'" and such", "val2": "And here is yet another '"value'" that is messed up by quotation marks", "val3": "etc. etc."}

试试这个指令:

首先将"替换为'"

并按照以下方式再次替换为正则表达式:

$a='{"val1": "This is "some value" that is inside of the "string" and such", "val2": "And here is yet another "value" that is messed up by quotation marks", "val3": "etc. etc."}';
var_dump($a);
$a=str_replace('"',''"',$a);
var_dump($a);
$re = "~('''''")([^'":]+)('''''"):''s*('''''")([^,]+)('''''")([,}])~m"; 
$str =$a;
$subst = "'"$2'": '"$5'"$7"; 
$a=preg_replace($re, $subst, $str);
var_dump($a);

现场演示

输出:

string '{"val1": "This is "some value" that is inside of the "string" and such", "val2": "And here is yet another "value" that is messed up by quotation marks", "val3": "etc. etc."}' (length=173)
string '{'"val1'": '"This is '"some value'" that is inside of the '"string'" and such'", '"val2'": '"And here is yet another '"value'" that is messed up by quotation marks'", '"val3'": '"etc. etc.'"}' (length=191)
string '{"val1": "This is '"some value'" that is inside of the '"string'" and such", "val2": "And here is yet another '"value'" that is messed up by quotation marks", "val3": "etc. etc."}' (length=179)