繁体   English   中英

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

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

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

Hello  
World   
John  
play  
football  

我想在读取这个文本文件的时候删除换行符,但是我不知道它看起来像文件 .txt 并且它的编码是 utf-8

只需使用带有FILE_IGNORE_NEW_LINES标志的file功能FILE_IGNORE_NEW_LINES

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

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

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

如果您打算将行放入数组中,那么假设文件大小合理,则可以尝试这样的操作。

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

*/

对于 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);

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

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