在 Windows 環境下,文字檔換行符為 `\r\n`(十六進位 `0x0D 0x0A`)。使用 `fgets()` 逐行讀取時,每行字串尾端會包含這兩個字元,導致 `strlen("123")` 回傳 5 而非 3,進而影響後續比對、切割、資料庫寫入等邏輯。
<?php
$file = 't1.txt';
$fp = fopen($file, 'w');
fwrite($fp, "123\r\n123\r\n"); // 寫入兩行
fclose($fp);
$fp = fopen($file, 'r');
while (!feof($fp)) {
$line = fgets($fp);
echo "長度: " . strlen($line) . " | 內容: [" . $line . "]
";
}
fclose($fp);
/* 輸出:
長度: 5 | 內容: [123
]
長度: 5 | 內容: [123
]
長度: 0 | 內容: []
*/
$line = rtrim($line, "\r\n"); // 僅移除行尾換行符,保留前導空白
$line = str_replace(["\r\n", "\r", "\n"], '', $line); // 移除所有換行符
$len = strlen($line);
if ($len >= 2 && substr($line, -2) === "\r\n") {
$line = substr($line, 0, -2);
} elseif ($len >= 1 && in_array(substr($line, -1), ["\n", "\r"])) {
$line = substr($line, 0, -1);
}
<?php
function read_lines_clean(string $path): array
{
$lines = [];
$fp = fopen($path, 'r');
if ($fp) {
while (($line = fgets($fp)) !== false) {
$lines[] = rtrim($line, "\r\n");
}
fclose($fp);
}
return $lines;
}
// 使用
$data = read_lines_clean('t1.txt');
// $data = ['123', '123'];
原文摘自 zuodefeng 筆記