【问题标题】:read a text file with PHP and display all text after a certain string使用 PHP 读取文本文件并在某个字符串之后显示所有文本
【发布时间】:2011-10-22 16:11:07
【问题描述】:

我有一个包含大量文本的文本文件,我想用 PHP 在屏幕上显示其中的一部分。

在某个时刻,有ITEM DESCRIPTION:这样的字符串

我想从这个字符串(就在它之后)获取所有内容到文件末尾。

这是我目前的代码:

$file = "file.txt";
$f = fopen($file, "r");
while ($line = fgets($f, 1000))
  echo $line;

:)

【问题讨论】:

    标签: php string file text


    【解决方案1】:

    使用 strstr() 和 file_get_contents() 怎么样?

    $contents = strstr(file_get_contents('file.txt'), 'ITEM DESCRIPTION:');
    # or if you don't want that string itself included:
    $s = "ITEM DESCRIPTION:"; # think of newlines as well "\n", "\r\n", .. or just use trim()
    $contents = substr(strstr(file_get_contents('file.txt'), $s), strlen($s));
    

    【讨论】:

      【解决方案2】:
      $file = "file.txt";
      $f = fopen($file, 'rb');
      $found = false;
      while ($line = fgets($f, 1000)) {
          if ($found) {
             echo $line;
             continue;
          }
          if (strpos($line, "ITEM DESCRIPTION:") !== FALSE) {
            $found = true;
          }
      }
      

      【讨论】:

      • 糟糕。对不起。 strpos 参数是相反的。我会编辑答案。
      【解决方案3】:

      怎么样

      $file = "file.txt";
      $f = fopen($file, "r");
      $start = false;
      while ($line = fgets($f, 1000)) {
        if ($start) echo $line;
        if ($line == 'ITEM DESCRIPTION') $start = true;
      }
      

      ?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        相关资源
        最近更新 更多