You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

联系表单无法正常工作:PHP函数eregi已弃用,如何替换为preg_match?

我有一个老旧HTML网站上的咨询表单,此前在旧版PHP环境下运行正常,现在的问题是代码中使用的eregi()函数在所有新版PHP中都已被弃用。
我并不太清楚这部分代码的运行逻辑 :)
以下是包含eregi()部分的现有代码:

// check for any human hacking attempts
class clean {
    function comments($message) {
        $this->naughty = false;
        $this->message = $message;
        $bad = array("content-type","bcc:","to:","cc:","href");
        $for = array( "\r", "\n", "%0a", "%0d");
        foreach($bad as $b) {
            if(eregi($b, $this->message)) {
                $this->naughty = true;
            }   
        }   
        $this->message = str_replace($bad,"#removed#", $this->message);
        $this->message = stripslashes(str_replace($for, ' ', $this->message));
        
        // check for HTML/Scripts
        $length_was = strlen($this->message);
        $this->message = strip_tags($this->message);
        if(strlen($this->message) < $length_was) {
            $this->naughty = true;
        }
   }
} // class

我搜索后猜测需要将eregi()部分替换为preg_match(),但不知道该怎么在上述代码中修改才能正常运行,请问有人有解决思路吗?
提前感谢,顺颂时祺
Brian

修复方案

核心修改思路

eregi()是旧版PHP中不区分大小写的正则匹配函数,新版PHP已完全移除该函数。由于你当前的场景只是匹配固定的危险关键词,不需要用到正则功能,更推荐用stripos(不区分大小写的字符串查找函数)替代,性能更高且不会出现正则特殊字符报错的问题。

具体修改方式

只需要替换循环中的判断行即可:

// 原代码
if(eregi($b, $this->message)) {
// 替换后代码
if(stripos($this->message, $b) !== false) {

如果一定要按你搜索到的思路用preg_match替换,写法如下(需要加正则界定符和不区分大小写的i修饰符,同时转义特殊字符):

if(preg_match('/'.preg_quote($b, '/').'/i', $this->message)) {

完整修改后代码(采用更推荐的stripos方案)

// 检测恶意提交内容
class clean {
    function comments($message) {
        $this->naughty = false;
        $this->message = $message;
        // 恶意关键词列表,主要用于防范邮件头注入
        $bad = array("content-type","bcc:","to:","cc:","href");
        // 换行符替换列表
        $for = array( "\r", "\n", "%0a", "%0d");
        foreach($bad as $b) {
            // 不区分大小写检测是否包含恶意关键词
            if(stripos($this->message, $b) !== false) {
                $this->naughty = true;
            }   
        }   
        // 替换恶意关键词
        $this->message = str_replace($bad,"#removed#", $this->message);
        // 替换换行符、去除转义反斜杠
        $this->message = stripslashes(str_replace($for, ' ', $this->message));
        
        // 检测是否包含HTML/脚本标签
        $length_was = strlen($this->message);
        $this->message = strip_tags($this->message);
        if(strlen($this->message) < $length_was) {
            $this->naughty = true;
        }
   }
}

原代码逻辑说明

这段代码的作用是过滤用户提交的表单内容,防范常见的攻击行为:

  • 检测内容中是否包含邮件头注入常用的关键词,命中则标记为恶意内容
  • 自动替换删除恶意关键词和换行符,避免拼接邮件时被注入额外的邮件头
  • 自动过滤所有HTML标签,防范XSS跨站脚本攻击,如果原内容包含HTML标签也会被标记为恶意

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:39:04