remove new line characters from txt file using php

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

Leave a Comment