textarea 使用者輸入的換行 (\n、\r\n) 與空格在 HTML 中預設不顯示,需轉換為 <br> 與 才能正確渲染。
function htmlEncode($content) {
// 先處理空格,再處理換行,避免 被再次替換
$content = str_replace(' ', ' ', $content);
$content = str_replace("\n", '
', $content);
$content = str_replace("\r", '', $content); // 移除殘留 \r
return $content;
}
echo nl2br(htmlspecialchars($content));
// nl2br() 自動將 \n/\r\n/\r 轉
,htmlspecialchars() 防 XSS
優點:標準化、自動處理多種換行格式、搭配 htmlspecialchars() 安全。
function codeEncode($code) {
$code = htmlspecialchars($code);
$code = str_replace(' ', ' ', $code);
$code = nl2br($code);
return "{$code}";
}
htmlspecialchars() 防 XSS,再 nl2br() 或自訂替換。
3. 若需 WYSIWYG,考慮儲存 HTML (經過 Purifier 淨化) 或 Markdown。