我有一个 php 解析器,它通过换行符分割给定的字符串,执行如下操作:
I have a php parser that split a given string by line-breaks, doing something like this:
$lines = explode(PHP_EOL,$content);解析器在服务器端工作时工作正常.但是,当我通过 ajax(使用 jquery 的 $.post 方法)通过 post 传递内容时,问题出现了:无法识别换行符.因此,经过近一个小时的测试和头痛,我决定将 PHP_EOL 更改为 " " 并且它起作用了:
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 = expand(" ",$content);
$lines = explode(" ",$content);
现在可以了!该死的我浪费了太多时间!有人可以解释一下什么时候正确使用 PHP_EOL 和 " " 以便我将来可以节省时间吗?感谢您的回答;)
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 ;)
推荐答案常量PHP_EOL 通常应该用于特定平台的输出.
The constant PHP_EOL should generally be used for platform-specific output.
- 主要用于文件输出.
- 实际上文件函数已经在 Windows 系统上转换了 ←→ 除非在 fopen(..., "wb") 中使用代码>二进制模式.
- Mostly for file output really.
- Actually the file functions already transform ←→ on Windows systems unless used in fopen(…, "wb") binary mode.
对于文件输入,你应该更喜欢 .虽然大多数网络协议 (HTTP) 都应该使用 ,但这并不能保证.
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:
或者立即使用file(..., FILE_IGNORE_NEW_LINES) 函数,离开对 PHP 或 auto_detect_line_endings 的 EOL 处理.
Or use the file(…, FILE_IGNORE_NEW_LINES) function right away, to leave EOL handling to PHP or auto_detect_line_endings.
更强大和更简洁的替代方法是使用 preg_split() 和正则表达式:
A more robust and terser alternative is using preg_split() and a regexp:
$lines = preg_split("/R/", $content);R 占位符 检测 + 的任意组合.所以最安全,甚至适用于经典 MacOS ≤ 9 文本文件(实践中很少见).
The R placeholder detects any combination of + . So would be safest, and even work for Classic MacOS ≤ 9 text files (rarely seen in practice).
强制性微优化注意事项:虽然正则表达式有成本,但令人惊讶的是,它通常比 PHP 中的手动循环和字符串后处理更快.
还有一些经典示例,您应该避免 PHP_EOL,因为它的平台歧义:
And there are a few classic examples where you should avoid PHP_EOL due to its platform-ambiguity:
- 手动生成网络协议负载,例如基于 fsockopen() 的 HTTP.
- 对于 mail() 和 MIME 构造(实际上,您不应该反正自己做很乏味).
- 文件输出,如果你想一致只写 Unix 换行符,而不管环境如何.
- 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.
更多推荐
我什么时候使用 PHP
发布评论