Should I use \ r or \ n to explode () the contents of a file in PHP?

I am creating a function that can take a string, which is either fetched via file_get_contents()

in a local text file, or something from a url, for example http://site.com/338383.txt

.

The file will be a tabbed file, with each item in the file on a separate line. Is it better to use \n

or \r

to a explode()

string and get an array of each string?

I noticed that it \n

doesn't work in some cases . I would like the sequential path to work all the time. Any thoughts?

+1


a source to share


4 answers


You can use file () to get the contents of a file as an array with separate lines.



+5


a source


As duckyflip points out , you can use file () to get an array of file strings. However, if you still need to explode (for some unknown reason), you should use the PHP constant PHP_EOL

instead of "\ n" as it is cross platform compatible.



+2


a source


The problem is that newline is defined differently for different encodings and "text / plain" platforms. A quick and dirty solution would probably be to use split and the regex "\ r \ n | \ r | \ n", however it may break in some Unicode files and has no meaning to "context". That is, if you have a file where LF (\ n) is used as an EOL marker, and there are some CRs that should have been saved, the CRs will be split as well.

+1


a source


You can use preg_split () to explode with / \ n \ r \\ n \ r / and then trim () each element to make sure there are no remaining spaces left (if needed).

0


a source







All Articles