使用 fgets()、file() 或 SplFileObject 按行讀取文件時,每行末尾通常包含換行符(\n、\r\n 或 \r),需去除後再處理。
<?php
$content = str_replace("\n", "", $content); // 僅去除 LF
// 或同時去除 CR 和 LF
$content = str_replace(["\n", "\r"], "", $content);
?>
優點:速度快、語意清晰。
缺點:若需保留行內空格需注意不影響其他空白字符。
<?php
$content = preg_replace('/\s/', '', $content); // 去除所有空白字符(含換行、制表、空格)
// 僅去除行尾換行
$content = preg_replace('/\r?\n$/', '', $content);
?>
注意:\s 會連同空格、制表符一起移除,可能導致數據丟失,建議針對性使用行尾匹配。
<?php
$line = trim($line); // 預設去除 \n \r \t \v \0 及普通空格
// 指定字符集
$line = trim($line, "\r\n"); // 僅去除首尾換行符
?>
優點:內置函數、性能好、語意明確。
適用:逐行讀取時對每行調用 trim() 最為簡潔高效。
<?php
$file = new SplFileObject('data.txt');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
foreach ($file as $line) {
// $line 已自動去除換行符且跳過空行
process($line);
}
?>
SplFileObject::DROP_NEW_LINE 標誌可自動移除行尾換行符,配合 SKIP_EMPTY 跳過空行,代碼最乾淨。
| 方法 | 適用場景 | 性能 |
|---|---|---|
| trim($line, "\r\n") | 逐行處理,保留行內空格 | ★★★★★ |
| str_replace(["\n","\r"], "", $str) | 整文件讀入後批量處理 | ★★★★☆ |
| preg_replace('/\r?\n$/', '', $str) | 需精確控制行尾匹配 | ★★★☆☆ |
| SplFileObject + DROP_NEW_LINE | 現代面向對象讀取,自動處理 | ★★★★★ |