Tutorial :Should I use \r or \n for explode()ing the contents of a file in PHP?



Question:

I'm creating a function which can accept a string which is either retrieved through file_get_contents() on a local text file, or something fetched from a url such as http://site.com/338383.txt.

The file will be a tab seperated file, with each item in the file being on its own line. Is it better to use \n or \r to explode() the string and get an array of each line?

I've noticed that in some cases \n doesn't work. I'd like a consistent way which works all the time. Any thoughts?


Solution:1

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


Solution:2

As duckyflip points out, you can use the file() function to get an array of file lines. However, if you still need to explode (for an unknown reason), you should use the PHP constant PHP_EOL instead of '\n' as this is cross-platform compliant.


Solution:3

Problem is that newline is defined differently for different "text/plain" encodings and platforms. The quick-and-dirty solution would probably be to use split and the regular expression "\r\n|\r|\n", however, it may break on some unicode files and it has no sense of "context". I.e. if you have a file where LF (\n) is used as a EOL marker, and there's some CRs there which should have been preserved, the CRs will be split on as well.


Solution:4

You can use preg_split () to explode by /\n\r|\n|\r/, and then trim () each item to make sure no trailing whitespace is remaining (if it’s appropriate).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »