【问题标题】:Scanning a Text File Line by Line in PHP在 PHP 中逐行扫描文本文件
【发布时间】:2012-07-31 18:06:03
【问题描述】:

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

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

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

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

谁能帮帮我!!!谢谢!!

【问题讨论】:

  • 您在哪一部分需要帮助?你遇到了什么障碍?
  • 我在示例数据中也看不到任何括号。您的意思是“双引号”吗?
  • 我进一步修改了我的问题。谢谢大家!括号也是一个错字,我的意思是双引号。

标签: php string file


【解决方案1】:

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

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

)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2013-06-14
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多