我有很多行是这样格式化的:
{"id":1,"Melbourne is the capital of Australia.","correct":0,"Canberra is the capital of Australia."},
我需要把它转换成这个新格式:
{"id":1,"statement":"Melbourne is the capital of Australia.","correct":0,"answerswer":"Canberra is the capital of Australia."},
我可以这样做,如果我能找到,"
在每行中的第一次和第二次出现
我不知道你在实践中需要多严格的模式,但这个应该可以工作
Regex: '('{".*?":'d+',)(.*)(".*?"'})'
替代:''1"statement":'2"answerswer":'3'
('{".*?":'d+',)
捕获从{
开始到,
第一次出现的文本,
(.*)
捕获上述模式和以下模式之间的文本。
(".*?"'})
捕获从,
最后出现到}
结尾的文本,
,其中捕获的内容分别到变量'1
, '2
, '3
。
从您希望regex也与
工作的新请求 {"id":3,"Paris is the capital of France.","correct":1,NULL}
解决方法是替换最后一个正则表达式
(".*?"'})
((?:".*?"|NULL)'})
(?:...)
是一个非捕获组,这意味着你想将一些模式分组在一起,但不捕获它们到变量,如'1
, '2
, '3
, ...
,
|
是一个替代。
看到演示
不使用preg_replace:
$str = '{"id":1,"Melbourne is the capital of Australia.","correct":0,"Canberra is the capital of Australia."}';
$str = explode(',',$str);
$str[1] = '"statement":'.$str[1];
$str[3] = '"answerswer":'.$str[3];
$str = implode(',',$str);
var_dump(json_decode($str, true));