One question I get a lot is “how do I explode a string into lines?”. The “default” approach, not necessarily bad, is the following:
$lines = explode( "\n", $string );
This is pretty simple and self explanatory. Use PHP’s explode() function and pass the newline \n character as a delimiter. This should work and yet, in some “strange” cases, it does not. First of all, the newline character or sequence of characters differs from OS to OS. On Microsoft operating systems, the newline is represented by a sequence of \r\n (carriage return – ASCII 10 & line feed – ASCII 13). On older Mac Operating Systems the newline char is \r (carriage return) while on *nix systems is \n. So the correct way to break a string into lines is to use all three of them as delimiters. The easiest way is with regular expressions and preg_split().
$lines = preg_split( '/\r\n|\r|\n/', $string );
If you have enough free time on your hands, you can try strtok or other, more exotic, methods.
Hey,
Thanks for the code it worked correctly and solved a big head ache for me.
If you are creating and manipulating the file only on the host, you may use the constant PHP_EOL which is guaranteed to have as value the platform-specific representation of EOL.
In such situations, explode(PHP_EOL,$string) is faster and cleaner.
OriginalCopy> I know, but if you switch from Windows to Linux hosting or vice-versa, you might still end up with some issues. My solution is bullet-proof
It looks like you are a real specialist. Did ya study about the matter? hrhr
Thanks very much
works !
I’m slowly trying to teach myself php. This simple line of code worked perfectly for what I needed. Thanks.
- M
Great code! Thanks!
This PHP code is a real wrestle for me. Can’t keep outsourcing the changes and have to do it myself. This one line of code saved me hours – many thanks
The code adapts great for many uses.
Thanks