Mindaugas Mindaugas - 6 months ago 26
PHP Question

Regex find first and second ," occurence in every line

I have a lot of lines formatted as this:

{"id":1,"Melbourne is the capital of Australia.","correct":0,"Canberra is the capital of Australia."},

I need it to be converted to this new format:

{"id":1,"statement":"Melbourne is the capital of Australia.","correct":0,"answer":"Canberra is the capital of Australia."},

I could do that if I could find the first and second occurence of
in each line


I don't know how strict is pattern you want in practice, but this one should work

Regex: '(\{".*?":\d+\,)(.*)(".*?"\})'

Substitution: '\1"statement":\2"answer":\3'


(\{".*?":\d+\,) capture text from the starting of { to the first occurrence of ,,

(.*) capture text between the the above pattern and the below pattern.

(".*?"\}) capture text from the last occurrence of , to the ending of },

where the capturings go to the variable \1, \2, \3 respectively.


From your new requirement that you want regex to be also work with

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

The solution is you just replace the last regex





(?:...) is a non-capturing group which means you want to group some pattern together but without capturing them to variable such as \1, \2, \3, ...,

| is an alternation.

see DEMO