doushe8577 2012-07-31 18:06
浏览 34

在PHP中逐行扫描文本文件

So I have been working recently on a questionnaire script in php and I wrote a tool that would output a single txt file with a list of questions, each on it's own line. The file would look like so..

1 "Shopping for items is very important to me.." 2 3 4 5s 6 //notice the 5s

2 "I love it when it is a rainy day" 4 8s 12 16 32s

The first number is the Questions id number. Next within the double quotes is the question itself.

The next numbers that follow are id's of other questions that relate to that questions.

In the case of "5s", that is a special question and I want the file reader to detect if the number has an s after it.

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

My question is how can I code something that will read the file in this order:

(1)..The Question's ID number..

("Shopping for items is very important to me..")...Then the actual question itself disregarding the double quotes

(2 3 4 5s 6)...Then the actual numbers while being aware that some may be 'special'.

Can Someone PLease Help Me!!! THANKS!!

  • 写回答

1条回答 默认 最新

  • dousao8152 2013-06-03 00:34
    关注

    Here's an example of processing the file in the format you provided:

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

    And the result you will get from print_r($data) is:

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

    I'm not exactly sure what you want to do with the related questions, so it is currently a string, but you could process this further into an array if you needed to.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题