【PHP】过滤富文本内容

小破孩
2025-03-13 / 0 评论 / 7 阅读 / 正在检测是否收录...
    /**
     * @Author:小破孩
     * @Email:3584685883@qq.com
     * @Time:2024/10/24 13:50
     * @param $text
     * @return string|string[]|null
     * @Description:过滤富文本
     */
    public static function filterRichText($text){
        // 定义要过滤的 SQL 关键字模式
        $sqlPatterns = [
            '/\b(SELECT|INSERT|UPDATE|DELETE|FROM|WHERE|AND|OR|JOIN|DROP|CREATE|ALTER|TRUNCATE|GRANT|REVOKE|SET)\b/i',
            '/\b(AS|LIKE|NOT|IN|BETWEEN|IS|NULL|COUNT|SUM|AVG|MIN|MAX)\b/i',
            '/\b(UNION|ALL|ANY|EXISTS)\b/i',
            '/\b(ORDER\s+BY|LIMIT)\b/i'
        ];
        // 定义要过滤的常见函数模式
        $functionPatterns = [
            '/\b(function\s+\w+\s*\([^)]*\))\b/i',
            '/\b(eval|exec|system|passthru|shell_exec|assert)\b/i'
        ];
        // 定义要过滤的特殊字符和表达式模式
        $specialPatterns = [
            '/\$\{.*?\}/', // 过滤类似 ${expression} 的表达式
            '/@.*?;/', // 过滤以 @ 开头并以 ; 结尾的表达式
            '/\b(phpinfo|var_dump)\b/i', // 过滤特定的 PHP 函数
            '/<\s*(script|iframe|object|embed|applet)[^>]*>/i' // 过滤危险的脚本标签
        ];
        // 定义要过滤的危险属性模式
        $dangerousAttributesPatterns = [
            '/on\w+\s*=/i', // 过滤以 "on" 开头的事件属性
            '/javascript:[^"]*"/i' // 过滤 JavaScript 协议的链接
        ];
        // 先过滤 SQL 关键字
        $filteredText = preg_replace($sqlPatterns, '', $text);
        // 再过滤函数
        $filteredText = preg_replace($functionPatterns, '', $filteredText);
        // 然后过滤特殊字符和表达式
        $filteredText = preg_replace($specialPatterns, '', $filteredText);
        // 接着过滤危险的属性
        $filteredText = preg_replace($dangerousAttributesPatterns, '', $filteredText);
        // 处理可能出现的连续空格
        $filteredText = preg_replace('/\s+/', ' ', $filteredText);
        // 去除前后的空格
        $filteredText = trim($filteredText);
        // 转换 HTML 实体
        $filteredText = htmlentities($filteredText, ENT_QUOTES, 'UTF-8');

        return $filteredText;
    }
0

评论

博主关闭了所有页面的评论