2016-09-18 120 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));