gpt4 book ai didi

php - 使用 PHP 检测 EOL 类型

转载 作者:可可西里 更新时间:2023-10-31 22:09:53 25 4
gpt4 key购买 nike

Reference: This is a self-answered question. It was meant to share the knowledge, Q&A style.

如何检测 end of line 的类型PHP 中的字符?

PS:我已经从头开始编写这段代码太久了,所以我决定在 SO 上分享它,另外,我相信有人会找到改进的方法。

最佳答案

/**
* Detects the end-of-line character of a string.
* @param string $str The string to check.
* @param string $default Default EOL (if not detected).
* @return string The detected EOL, or default one.
*/
function detectEol($str, $default=''){
static $eols = array(
"\0x000D000A", // [UNICODE] CR+LF: CR (U+000D) followed by LF (U+000A)
"\0x000A", // [UNICODE] LF: Line Feed, U+000A
"\0x000B", // [UNICODE] VT: Vertical Tab, U+000B
"\0x000C", // [UNICODE] FF: Form Feed, U+000C
"\0x000D", // [UNICODE] CR: Carriage Return, U+000D
"\0x0085", // [UNICODE] NEL: Next Line, U+0085
"\0x2028", // [UNICODE] LS: Line Separator, U+2028
"\0x2029", // [UNICODE] PS: Paragraph Separator, U+2029
"\0x0D0A", // [ASCII] CR+LF: Windows, TOPS-10, RT-11, CP/M, MP/M, DOS, Atari TOS, OS/2, Symbian OS, Palm OS
"\0x0A0D", // [ASCII] LF+CR: BBC Acorn, RISC OS spooled text output.
"\0x0A", // [ASCII] LF: Multics, Unix, Unix-like, BeOS, Amiga, RISC OS
"\0x0D", // [ASCII] CR: Commodore 8-bit, BBC Acorn, TRS-80, Apple II, Mac OS <=v9, OS-9
"\0x1E", // [ASCII] RS: QNX (pre-POSIX)
//"\0x76", // [?????] NEWLINE: ZX80, ZX81 [DEPRECATED]
"\0x15", // [EBCDEIC] NEL: OS/390, OS/400
);
$cur_cnt = 0;
$cur_eol = $default;
foreach($eols as $eol){
if(($count = substr_count($str, $eol)) > $cur_cnt){
$cur_cnt = $count;
$cur_eol = $eol;
}
}
return $cur_eol;
}

注意事项:

  • 需要检查编码类型
  • 需要以某种方式知道我们可能在像 ZX8x 这样的奇异系统上(因为 ASCII x76 是一个普通字母) @radu 提出了一个很好的观点,就我而言,不值得为此付出努力很好地处理 ZX8x 系统。
  • 我应该将函数分成两部分吗? mb_detect_eol()(多字节)和 detect_eol()

关于php - 使用 PHP 检测 EOL 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com