前端 `
<textarea><?php echo $content; ?></textarea>
↑ 這裡的縮進換行會成為內容一部分!
PHP 模板中 `
<!-- 錯誤 -->
<textarea>
<?php echo $content; ?>
</textarea>
<!-- 正確 -->
<textarea><?php echo $content; ?></textarea>
// 移除所有空格
echo str_replace(' ', '', $content);
// 或使用 strtr (效能略優)
echo strtr($content, [' ' => '']);
// 僅清理首尾空白 (推薦)
echo trim($content);
| 環境 | 換行符 | PHP 轉義寫法 |
|---|---|---|
| Windows (textarea 提交) | \r\n (CRLF) | "\r\n" |
| Linux/Mac | \n (LF) | "\n" |
| HTML 顯示 | <br /> | nl2br() |
function normalize_linebreaks($text) {
return str_replace(["\r\n", "\r"], "\n", $text);
}
// 存儲時統一為 \n
$content = normalize_linebreaks(trim($_POST['content']));
核心原則:模板不縮進 textarea 內容、入庫 trim、讀出 htmlspecialchars、顯示 nl2br,四步走徹底解決空格換行困擾。