【问题标题】:remove new line characters from txt file using php使用php从txt文件中删除换行符
【发布时间】:2012-04-13 03:40:21
【问题描述】:

我有一个txt文件,它的内容是这样的

Hello  
World   
John  
play  
football  

我想在阅读这个文本文件时删除换行符,但我不知道它是什么样子 文件 .txt,其编码为 utf-8

【问题讨论】:

  • Mira,你想用什么都没有替换,还是用其他类型的空格?

标签: php newline text-files


【解决方案1】:

对于 PHP 的 file() 函数,FILE_IGNORE_NEW_LINES 标志是要走的路。如果您以其他方式获取数组,例如 gzfile(),请执行以下操作:

// file.txt
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

// file.txt.gz
$lines = gzfile('file.txt.gz');
$lines = array_map(function($e) { return rtrim($e, "\n\r"); }, $lines);

【讨论】:

    【解决方案2】:

    只需使用带有FILE_IGNORE_NEW_LINES 标志的file 函数。

    file 读取整个文件并返回一个包含所有文件行的数组。

    默认情况下,每一行的末尾都包含换行符,但我们可以通过FILE_IGNORE_NEW_LINES 标志强制修剪。

    所以很简单:

    $lines = file('file.txt', FILE_IGNORE_NEW_LINES);
    

    结果应该是:

    var_dump($lines);
    array(5) {
        [0] => string(5) "Hello"
        [1] => string(5) "World"
        [2] => string(4) "John"
        [3] => string(4) "play"
        [4] => string(8) "football"
    }
    

    【讨论】:

    • 你也可以使用这个:$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)。这样你也可以跳过空的新行!
    【解决方案3】:

    如果您要将行放入数组中,假设文件大小合理,您可以尝试这样的事情。

    $file = 'newline.txt';      
    $data = file_get_contents($file);   
    $lines = explode(PHP_EOL, $data);  
    
    /** Output would look like this
    
    Array
    (
        [0] => Hello  
        [1] => World   
        [2] => John  
        [3] => play  
        [4] => football  
    )
    
    */
    

    【讨论】:

      【解决方案4】:

      我注意到它在问题中的粘贴方式,这个文本文件似乎在每行的末尾都有空格字符。我会认为那是偶然的。

      <?php
      
      // Ooen the file
      $fh = fopen("file.txt", "r");
      
      // Whitespace between words (this can be blank, or anything you want)
      $divider = " ";
      
      // Read each line from the file, adding it to an output string
      $output = "";
      while ($line = fgets($fh, 40)) {
        $output .= $divider . trim($line);
      }
      fclose($fh);
      
      // Trim off opening divider
      $output=substr($output,1);
      
      // Print our result
      print $output . "\n";
      

      【讨论】:

      • 当任何单词超过 40 个字节时,结果将无效(更不用说它仅适用于每行单个单词)trim 不是一个好的选择,如果 - 就足够了使用 rtrim (您只需要修剪右侧) - 不要忘记第二个参数,它是一个字符掩码。默认情况下,它将修剪:空格、制表符、新行、回车、空字节和垂直制表符。
      【解决方案5】:

      有不同种类的换行符。这将删除 $string 中的所有 3 种:

      $string = str_replace(array("\r", "\n"), '', $string)
      

      【讨论】:

      • 有2种还是3种?
      • @Mira,3 种(\r\n\r\n),我的答案中的脚本负责 3。
      猜你喜欢
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多