cls_string_filter 工具類完整實作
<?php
class cls_string_filter {
// \n 轉 <br/>
static public function nl2br($string) {
return nl2br($string);
}
// <br/> 轉 \n
static public function br2nl($string) {
$array = array('<br>', '<br/>');
return str_replace($array, "\n", $string);
}
// 多重空白合併為單一空白
static public function merge_spaces($string) {
return preg_replace("/\s(?=\s)/", "\\1", $string);
}
// 多重 <br/> 合併為單一
static public function merge_brs($string) {
return preg_replace("/((<br\/?>)+)/i", "<br>", $string);
}
// 移除 HTML 標籤
static public function strip_tags($string) {
return strip_tags($string);
}
// 大小寫轉換
static public function strtolower($string) { return strtolower($string); }
static public function strtoupper($string) { return strtoupper($string); }
// 修剪指定字元(預設修剪空白)
static public function trim($string, $char_list = '\\s') {
$find = array('/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//');
$replace = array('\\\\\\0', '\\', '\/');
$char = preg_replace($find, $replace, $char_list);
$pattern = '^['.$char.']*|['.$char.']*$';
return preg_replace("/$pattern/sSD", '', $string);
}
// 移除 <style> 腳本
static public function strip_style($string) {
$reg = "/<style[^>]*>.*?<\/style>/is";
return preg_replace($reg, '', $string);
}
// 移除危險 HTML 標籤(XSS 基礎防護)
static public function strip_html_tags($string) {
$reg = "/(\/?)(script|iframe|style|html|body|title|meta|\?|\%)([^>]*>)/is";
return preg_replace($reg, '', $string);
}
}
?>
各方法適用情境
| 方法 | 用途 | 注意事項 |
| nl2br / br2nl | 前後端換行格式互轉 | 儲存用 \n,顯示用 <br> |
| merge_spaces | 清理使用者輸入多餘空白 | 正則使用 positive lookahead |
| merge_brs | 防止連續換行撐版 | 不區分大小寫匹配 |
| strip_tags | 取純文字摘要 | 無法處理已編碼的標籤 |
| strip_style | 移除內嵌 CSS 防樣式污染 | 貪婪匹配需謹慎 |
| strip_html_tags | 基礎 XSS 過濾 | 非完整方案,建議搭配 HTMLPurifier |
安全性補充建議
- strip_html_tags 非完整 XSS 方案:繞過手法眾多,生產環境必須使用 HTMLPurifier 或 DOMPurify
- 資料庫存儲建議保留原始輸入,輸出時再依語境編碼
- 現代框架(Laravel、Symfony)內建更完善的字串處理與防護機制