替换"使用\",只有在"

时间:2015-01-09 15:01:52

标签: 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."}

应改为:

{"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."}

1 个答案:

答案 0 :(得分:0)

尝试使用此说明:

首先将"替换为\"

然后通过正则表达式再次替换:

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

live demo

<强>输出:

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)