Php 替换“;加上\";,仅当用“报价”括起时;

Php 替换“;加上\";,仅当用“报价”括起时;,php,regex,Php,Regex,我正在从数据库中读取一个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."}

我正在从数据库中读取一个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."}

尝试以下说明:

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)
首先,将
替换为
\”

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

$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)

哈哈,你怎么知道你什么时候碰到了一个结束语
”?json_到底是如何编码“不工作”的?json_encode不可能产生无效的json。它要么成功,要么返回布尔值false。它不会返回无效的json字符串。请修复您的数据库插入代码或放弃手动json构造。你无法可靠地修复损坏。(顺便说一句,你试过什么吗?)我同意马里奥的观点,你需要解决问题的根本原因。出于好奇,如果用单引号封装字符串会发生什么?json_encode会转义“.”的所有出现。当使用单引号时,它会起作用-所以现在我将避免使用双引号,直到我可以按照建议修复插入。