用戶在 <textarea> 輸入多行文字,後端需輸出為 HTML 並保留原有換行、段落結構。
function shtm($design_str) {
$str = trim($design_str); // 去除首尾空白
$str = str_replace("\r\n", "<br>", $str); // Windows 換行轉 br
$str = str_replace("\n", "<br>", $str); // Unix 換行轉 br
$str = str_replace("\r", "<br>", $str); // Mac 老式換行轉 br
// 可選:將連續 br 包裝為 p 標籤
// $str = '<p>' . str_replace('<br><br>', '</p><p>', $str) . '</p>';
return $str;
}
function shtm_advanced($text) {
$text = trim($text);
// 統一換行符為 \n
$text = str_replace(["\r\n", "\r"], "\n", $text);
// 分割段落 (連續空行視為段落分隔)
$paragraphs = preg_split('/\n\s*\n/', $text);
$html = '';
foreach ($paragraphs as $para) {
$lines = explode("\n", trim($para));
$html .= '<p>' . implode('<br>', $lines) . '</p>';
}
return $html;
}
| 函數 | 用途 |
|---|---|
nl2br() | 內建函數,將 \n 轉 <br> (PHP 4.0.5+) |
htmlspecialchars() | 轉義 HTML 特殊字元,防 XSS |
strip_tags() | 移除 HTML/JS 標籤 |
wordwrap() | 按寬度自動換行 |