在PHP中逐行扫描文本文件


Scanning a Text File Line by Line in PHP

所以我最近一直在php中编写一个问卷脚本,我写了一个工具,可以输出一个带有问题列表的txt文件,每个问题都在自己的行上。文件看起来像…

1"购物对我来说非常重要……"2 3 4 5s 6 //注意5s

2"我喜欢下雨天"4 8s 12 16 32s

第一个数字是Questions id编号。下一个双引号是问题本身。

接下来的数字是与该问题相关的其他问题的id。

在"5s"的情况下,这是一个特殊的问题,我希望文件读取器检测数字后面是否有s。

$file = fopen("output.txt", "r");
$data = array();
while (!feof($file)) 
{
   $data[] = fgets(trim($file));
}
fclose($file);
// Now I have an Array of strings line by line
// Whats next now?? 

我的问题是,我如何才能编码一些将按以下顺序读取文件的内容:

(1) 。。问题的ID号。。

("购物对我来说非常重要…")…然后实际问题本身就忽略了双引号

(2 3 4 5s 6)。。。然后是实际数字,同时要意识到有些数字可能是"特殊的"。

有人能帮帮我吗!!!谢谢!!

以下是以您提供的格式处理文件的示例:

$file = fopen("output.txt", "r");
$data = array();
while (!feof($file)) {
   $line = trim(fgets($file, 2048));
   if (preg_match('/^('d+)'s+"([^"]+)"'s*(['ds's]+)?$/', $line, $matches)) {
        $data[] = array(
            'num' => $matches[1],
            'question' => $matches[2],
            'related' => $matches[3],
        );
   }
}
fclose($file);
print_r($data);

从print_r($data)得到的结果是:

Array
(
    [0] => Array
        (
            [num] => 1
            [question] => Shopping for items is very important to me..
            [related] => 2 3 4 5s 6
        )
    [1] => Array
        (
            [num] => 2
            [question] => I love it when it is a rainy day
            [related] => 4 8s 12 16 32s
        )
)

我不太确定你想对相关问题做什么,所以它目前是一个字符串,但如果需要,你可以将其进一步处理成一个数组。