remove new line characters from txt file using php

2019-01-15 09:43发布

问题:

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

回答1:

There are different kind of newlines. This will remove all 3 kinds in $string:

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


回答2:

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


回答3:

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  
)

*/


回答4:

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