简体   繁体   English

使用php从txt文件中删除换行符

[英]remove new line characters from txt file using php

I have txt file its content like this我有 txt 文件,它的内容是这样的

Hello  
World   
John  
play  
football  

I want to delete the new line character when reading this text file, but I don't know how it look like the file .txt and its encoding is utf-8我想在读取这个文本文件的时候删除换行符,但是我不知道它看起来像文件 .txt 并且它的编码是 utf-8

Just use file function with FILE_IGNORE_NEW_LINES flag. 只需使用带有FILE_IGNORE_NEW_LINES标志的file功能FILE_IGNORE_NEW_LINES

The file reads a whole file and returns an array contains all of the file lines. file读取整个文件,并返回包含所有文件行的数组。

Each line contains new line character at their end as default, but we can enforce trimming by FILE_IGNORE_NEW_LINES flag. 默认情况下,每一行的末尾都包含换行符,但是我们可以通过FILE_IGNORE_NEW_LINES标志强制执行修整。

So it will be simply: 因此,它将很简单:

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

The result should be: 结果应为:

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"
}

There are different kind of newlines. 有不同种类的换行符。 This will remove all 3 kinds in $string : 这将删除$string中的所有3种:

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

If your going to be putting the lines into an array, an assuming a reasonable file size you could try something like this. 如果您打算将行放入数组中,那么假设文件大小合理,则可以尝试这样的操作。

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

*/

For PHP's file() function, the FILE_IGNORE_NEW_LINES flag is the way to go.对于 PHP 的file()函数, FILE_IGNORE_NEW_LINES标志是要走的路。 In case you get your array in another way, like with gzfile() , do this:如果您以另一种方式获取数组,例如使用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);

I note that the way it was pasted in the question, this text file appears to have space characters at the end of each line. 我注意到该文本文件在问题中的粘贴方式,每行末尾似乎都有空格字符。 I'll assume that was accidental. 我认为那是偶然的。

<?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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM