【问题标题】:How to remove lines containing a specific character (#) from file and echo out the data using PHP如何从文件中删除包含特定字符 (#) 的行并使用 PHP 回显数据
【发布时间】:2018-04-24 16:08:22
【问题描述】:

我有一个包含如下数据的文本文件:

#dacdcadcasvsa
#svsdvsd
#  
#sfcnakjncfkajnc
I want to keep this line
and this one

如何删除所有包含 # 的行并回显不包含的行,如下所示:

I want to keep this line
and this one

我只知道我必须 get_file_contents($filename)。我必须把它放在一个数组中吗?

任何提示和指导将不胜感激。

【问题讨论】:

标签: php arrays


【解决方案1】:

使用file()foreach()

$lines = file("a.txt");
foreach ( $lines as $line ) {
    if ( $line[0] != '#' ){
        echo $line;
    }
}

只需更新文件名即可。

【讨论】:

  • 您在输出行后缺少换行符。另外,我更喜欢SplFileObject()file()(因为它是面向对象的并且可以处理大文件)。
  • @masterfloda - 来自文档 - '数组的每个元素都对应于文件中的一行,换行符仍然附加'。尽管如果您不确定文件的大小,SplFileObject() 是有效的。
  • 哦。我应该有 RTFM :-)
【解决方案2】:

您可以在输出之前将所有注释行替换为空字符串。

<div style="white-space: pre-line;">
    <?= preg_replace('/^#.*\n/m', '', file_get_contents($filename)) ?>
</div>

【讨论】:

    【解决方案3】:

    你的想法是正确的;虽然您需要的 PHP 方法(函数)实际上是 file_get_contents(),而不是 get_file_contents()(根据您的问题)。

    让我们分解一下:

    • 我们需要一种将数据分离成可排序块的方法。正如您所说,最好的方法是使用数组。
    • 我们可以这样做,使用井号 (#) 作为分隔符 - 但这 意味着最后一块文本是我们想要的文本的混合 删除,以及我们要保留的文本。相反,我们将使用 line 分隔符作为我们的分隔符。
    • 数据分离后,我们可以删除那些以井号开头的行。

    我们的代码将如下所示:

    <?php
        // Get the file contents
        $fileContents = file_get_contents('my_file.txt'); // This could be any file extension
    
        // Split the file by new lines
        $contentsArr = preg_split('/\r\n|\r|\n/', $fileContents);
    
        // Function for removing items from an array - https://stackoverflow.com/questions/9993168/remove-item-from-array-if-item-value-contains-searched-string-character?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
        function myFilter($string) {
            return strpos($string, '?') === false;
        }
    
        // Remove comment items from array
        $newFileContents = array_filter($fileContents, 'myFilter');
    
        // Concatenate and echo out the result
        echo implode(",\n",$newFileContents);
    

    【讨论】:

      【解决方案4】:

      因为无聊所以换了一个:

      foreach(preg_grep('/^#/', file($filename), PREG_GREP_INVERT) as $line) {
          echo $line;
      }
      
      • 将文件行读入数组
      • 获取所有不以^ # 字符开头的行
      • 循环这些行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 2018-06-28
        • 1970-01-01
        • 2021-10-24
        • 2011-09-05
        相关资源
        最近更新 更多