简体   繁体   中英

remove new line characters from txt file using php

I have txt file its content like this

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

Just use file function with FILE_IGNORE_NEW_LINES flag.

The file reads a whole file and returns an array contains all of the file lines.

Each line contains new line character at their end as default, but we can enforce trimming by FILE_IGNORE_NEW_LINES flag.

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 = 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. In case you get your array in another way, like with gzfile() , do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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