【发布时间】:2020-03-29 12:20:10
【问题描述】:
有人可以帮我解决 json 文件中的 str_replace 值吗? 我的代码在替换字符串上运行良好,但它对 json 中的值不起作用。
在所有 json 文件中正确地将“旧”替换为“新”:
foreach(glob('*.json') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace('old','new',$file_contents);
file_put_contents($path_to_file,$file_contents);
}
但是当我需要将 "min_order":"" 替换为 "min_order":"1" 时,它不起作用。我不能直接用"1" 替换"",因为我在json 中有很多其他值。
我测试了这段代码,但是没有用:
foreach(glob('*.json') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace('"min_order":""','"min_order":"1"',$file_contents);
file_put_contents($path_to_file,$file_contents);
}
有人可以帮我解决这个问题吗?
提前谢谢你。 吉日
【问题讨论】:
-
之前转换为数组。不要尝试编辑 json 字符串!
-
在 JSON 字符串上使用
str_replace()会导致各种问题,我原以为这是您最不想做的事情。"min_order":""可能以"min_order" : ""或"min_order": ""的形式出现,因此它会因各种原因而失败。
标签: php json replace str-replace