Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

php - When do I use PHP_EOL instead of and vice-versa ? Ajax/Jquery client problem

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 " " and it worked:

$lines = explode(" ",$content);

Now it works! Damn it I lost so much time! Could somebody explain me when use PHP_EOL and " " properly, so I can save time in the future? Appreciate your kind answers ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The constant PHP_EOL should generally be used for platform-specific output.

  • Mostly for file output really.
  • Actually the file functions already transform ←→ on Windows systems unless used in fopen(…, "wb") binary mode.

For file input you should prefer however. While most network protocols (HTTP) are supposed to use , that's not guaranteed.

  • Therefore it's best to break up on and remove any optional manually:

    $lines = array_map("rtrim", explode("
    ", $content));
    

    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:

    $lines = preg_split("/R/", $content);
    

    The R placeholder detects any combination of + . So would be safest, and even work for Classic MacOS ≤ 9 text 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_EOL due to its platform-ambiguity:

  • Manual generation of network protocol payloads, such as HTTP over fsockopen().
  • For mail() and MIME construction (which really, you shouldn't do tediously yourself anyway).
  • File output, if you want to consistently write just Unix newlines regardless of environment.

So use a literal " " combination when not writing to files, but preparing data for a specific context that expects network linebreaks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...