【问题标题】:Reading certain lines of a textfile PHP读取文本文件的某些行 PHP
【发布时间】:2013-08-16 12:49:48
【问题描述】:

我必须为具有如下结构的 txt 文件编写解析器:

exampleOfSomething: 95428, anotherExample: 129, youNeedThis: 491,\n

anotherExample:30219,exampleOfSomething:4998,youNeedThis:492,

但是有一个主要问题 - 就像在示例中一样 - 文件并不总是以一个顺序出现,有时我会在“anotherExample”等之前得到“youNeedThis”,但结构

{变量}:{值},

总是一样的。我知道我在寻找什么(即我只想读取“anotherExample”的值)。当我得到这个数字时,我希望它在单独的行中将它写入某个 txt 文件:

129

30219

到目前为止,我将文件中的每个数字写在单独的行中,但我必须将它们过滤掉以仅包含我正在寻找的数字。有没有办法过滤掉这个而不必做这样的事情:

$c = 0;
if (fread($file, 1) == "a" && $c == 0) $c++;
if (fread($file, 1) == "n" && $c == 1) $c++;
if (fread($file, 1) == "o" && $c == 2) $c++;
// And here after I check if this is correct line, I take the number and write the rest of it to output.txt

【问题讨论】:

    标签: php parsing fread


    【解决方案1】:

    发现regular expressions

    preg_match_all('/anotherExample\:\s*([0-9]+)/sm', file_get_contents('input.txt'), $rgMatches);
    file_put_contents('output.txt', join(PHP_EOL, $rgMatches[1]));
    

    【讨论】:

      【解决方案2】:

      这样的事情怎么样:

      <?php
      
      $data = file_get_contents($filename);
      $entries = explode(",", $data);
      foreach($entries as $entry) {
          if(strpos($entry, "anotherExample") === 0) {
              //Split the entry into label and value, then print the value.
          }
      }
      
      ?>
      

      您可能想要做一些比explode 更强大的事情来获得$entries,比如preg_split

      【讨论】:

      • 是的,或者您可以使用正则表达式完成整个操作,就像 Alma Do Mundo 在他们的回答中建议的那样。
      【解决方案3】:

      我已经用这个解决了:

      $fileHandlerInput = file_get_contents($fileNameInput);
      $rows = explode (",", $fileHandlerInput);
      
      foreach($rows as $row) {
          $output = explode(":", $row);
          if (preg_match($txtTemplate, trim($output[0]))) {
              fwrite($fileHandlerOutput[0], trim($output[1])."\r");
          }
      }    
      

      这不是最有效也不是最整洁的方法,但它确实有效,两个答案都帮助我解决了这个问题。

      【讨论】:

        猜你喜欢
        • 2010-12-26
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多