PHP读取包含问与答的txt文件并创建数组或对象?

问题描述 投票:0回答:1

[我已经在moodle中看到了此功能,他们在其中上传.txt文件并解析数据并创建问题库。

样本:-

What is php?

A. Php is a language.

B. Php creates HTML.

C. Php is fun.

D. none of these.

ANSWER: D



Which is YII-2?

A. Framework.

B. Tool.

C. Code player.

D. None of these

ANSWER: A

到目前为止,我已经尝试过用它来解析它,但是我不知道要为批量上传实现它到底要做什么。

txt_file    = file_get_contents('path/to/file.txt');
$rows        = explode("\n", $txt_file);
array_shift($rows);

foreach($rows as $row => $data)
{

}

我正在尝试获取的数组

[
[
'question' => 'Php is a language.',
'options' => [
             'A' =>  'Php is a language.',
             'B' => 'Php creates HTML.',
             'C' => 'Php is fun.',
             'D' => 'none of these.'
             ],
'answer' => 'D'
],
.....
]

[Sample file:-文件代码fbSObnlghQkqroEk4lrQ

php regex parsing text
1个回答
0
投票

尝试(?mi)^(?![A-Z]\.)(?<question>.*?)\?\s*^A\.(?<A>.*)\s*(?:^B\.(?<B>.*)(?:\s*^C\.(?<C>.*)(?:\s*^D\.(?<D>.*)(?:\s*^E\.(?<E>.*))?)?)?)?\s*^ANSWER:\s*(?<answer>[A-F])

demo

循环匹配,从零件创建单个阵列,追加到更大的数组。不需要“选项”,但匹配后可以从A-E组创建子数组然后添加到单个数组。在下一场比赛中重复。

© www.soinside.com 2019 - 2024. All rights reserved.