2016-09-18 119 views
0

我有很多格式化,因为这行:正则表达式查找第一个和第二个” occurence在每一行

{"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,"answer":"Canberra is the capital of Australia."}, 

我可以做到这一点,如果我能找到,"的第一次和第二次发生在每一行

+0

在哪里这些线是从哪里来的?它们看起来像是在生成JSON时失败的尝试。修复这些数据的来源可能会更容易,因此它会输出有效的JSON,而不是在您的末端输入字符串... – Chris

回答

1

我不知道你想在实践中有多严格,但这个应该工作

正则表达式:'(\{".*?":\d+\,)(.*)(".*?"\})'

换人:'\1"statement":\2"answer":\3'

说明从{开始到的,第一次出现

(\{".*?":\d+\,)捕获文本时,上述间

(.*)捕获文本模式和下面的模式。从,的最后出现的}结束

(".*?"\})捕获文本,

其中capturings分别去变量\1\2\3

附加

从你的新的要求,你想正则表达式是也

{"id":3,"Paris is the capital of France.","correct":1,NULL}

该解决方案的工作是你刚刚替换最后一个正则表达式

(".*?"\})

((?:".*?"|NULL)\})

说明

(?:...)是一个非捕获组,这意味着要组一些图案在一起,但没有它们捕获到变量如\1\2\3...

|是一个交替。

看到DEMO

+0

我更新了它,请在DEMO链接上检查它。 – fronthem

+1

工程!谢谢 – Mindaugas

0

该方法没有的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] = '"answer":'.$str[3]; 
$str = implode(',',$str); 

var_dump(json_decode($str, true));