輸出純文字摘要、API 回傳資料、儲存用戶輸入前,常需移除 HTML 標籤、實體編碼、多餘空白等「雜質」。
function clean_string($string) {
$string = trim($string); // 移除首尾空白
$string = strip_tags($string); // 剝離 HTML/PHP 標籤
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); // 轉義特殊字元
$string = str_replace("\n", '', $string); // 移除換行符
$string = trim($string); // 再次修剪
return $string;
}
// 使用範例
echo clean_string('內 容 <br> <html> asdfeiuonsdfje');
// 輸出:內 容 asdfeiuonsdfje
針對連續空白、製表符、換行符的更徹底清理:
$str = " This line containstliberal rn use of whitespace.nn";
// 1. 移除首尾空白
$str = trim($str);
// 2. 合併連續空白字元為單一空格
$str = preg_replace('/\s+/', ' ', $str);
// 3. 將控制字元替換為空格
$str = preg_replace('/[\n\r\t]/', ' ', $str);
echo "<pre>{$str}</pre>";
// 輸出:This line contains liberal use of whitespace.
| 函式 | 用途 |
|---|---|
trim() | 移除字串首尾空白字元 |
strip_tags() | 剝離 HTML、XML 和 PHP 標籤 |
htmlspecialchars() | 將特殊字元轉為 HTML 實體 |
preg_replace() | 正則替換,處理複雜空白模式 |
strip_tags + htmlspecialchars 防 XSS