I have a php parser that split a given string by line-breaks, doing something like this:
$lines = explode(PHP_EOL,$content);
The parser works fine when working on server side. However, when I pass the content via post by ajax (using jquery's $.post method) the problem arises: line breaks are not recogniezed. So after almost an hour of tests and head-aches I decided to changed PHP_EOL by "n" and it worked:
$lines = explode("n",$content);
Now it works! Damn it I lost so much time! Could somebody explain me when use PHP_EOL and "n" properly, so I can save time in the future? Appreciate your kind answers ;)
PHP_EOLshould generally be used for platform-specific output.
rnon Windows systems unless used in
fopen(…, "wb")binary mode.
For file input you should prefer
nhowever. While most network protocols (HTTP) are supposed to use
rn, that's not guaranteed.
Therefore it's best to break up on
nand remove any optional
Or use the
file(…, FILE_IGNORE_NEW_LINES)function right away, to leave EOL handling to PHP or auto_detect_line_endings.
A more robust and terser alternative is using
preg_split()and a regexp:
Rplaceholder detects any combination of r + n. So would be safest, and even work for Classic MacOS
? 9text files (rarely seen in practice).
Obligatory microoptimization note:
While regex has a cost, it's surprisingly often speedier than manual loops and string postprocessing in PHP.
And there are a few classic examples where you should avoid
PHP_EOLdue to its platform-ambiguity:
mail()and MIME construction (which really, you shouldn't do tediously yourself anyway).
nnewlines regardless of environment.
So use a literal
"rn"combination when not writing to files, but preparing data for a specific context that expects network linebreaks.