首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 字串過濾與替換實用工具類:從換行轉換到 XSS 防護完整實作

     編輯:PHP 綜合知識

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)內建更完善的字串處理與防護機制
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved