0

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

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

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

第一个数字是问题 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)......然后是实际数字,同时意识到有些可能是“特殊的”。

有人可以帮帮我吗!!!谢谢!!

4

1 回答 1

0

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

$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
        )

)

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

于 2013-06-03T00:34:12.847 回答