如何用preg_match拦截单无意义词或无空格的表单垃圾信息
表单反垃圾验证规则实现方案
针对你提出的两个反垃圾规则,结合现有代码进行如下修改,同时规避合法缩写的误拦截:
规则1:拦截仅输入单个无意义词的提交
- 先定义允许的合法三字母大写缩写列表(可根据需求自行扩展)
- 检查
name和comments字段是否仅包含单个词,且该词不在合法缩写列表中 - 单个词的判断通过正则匹配无空格的纯字母/数字组合完成
规则2:拦截至少三个词无空格连写的提交
- 匹配连续多组含小写字母的字母块(无空格分隔),或长度过长的无空格纯字母字符串(覆盖垃圾信息的随机字母组合场景)
- 规避全大写的合法缩写,仅拦截混合大小写或纯小写的长串无空格内容
修改后的完整代码
<?php $name = $_POST['name']; $email_from = $_POST['email']; $telephone = $_POST['telephone']; $comments = $_POST['comments']; $error_message = ""; // 定义允许的合法大写缩写列表(可按需扩展) $allowed_acronyms = ['USA', 'STP', 'NRA', 'BBC', 'CNN']; // 规则1:拦截仅输入单个无意义词的情况(针对Name和Comments) // 检查Name字段 if (preg_match('/^\w+$/i', $name)) { $name_upper = strtoupper($name); if (!in_array($name_upper, $allowed_acronyms)) { $error_message .= "Invalid input format in Name.<br />"; } } // 检查Comments字段 if (preg_match('/^\w+$/i', $comments)) { $comments_upper = strtoupper($comments); if (!in_array($comments_upper, $allowed_acronyms)) { $error_message .= "Invalid input format in Message.<br />"; } } // 规则2:拦截至少三个词无空格连写的情况(针对Name和Comments) $no_space_pattern = '/(?:[a-z]+[A-Z]*[a-z]*){3,}|[A-Za-z]{10,}/i'; if (preg_match($no_space_pattern, $name)) { $error_message .= "Invalid continuous characters in Name.<br />"; } if (preg_match($no_space_pattern, $comments)) { $error_message .= "Invalid continuous characters in Message.<br />"; } // 原有垃圾词检测逻辑 if(preg_match('/http|www|audience|been seen before|bitcoin|business need|can I trust|completely new|content|create|dear friend|debt|dedicated team|design|developer|domain name|ensure|exciting|explosive|financial|first page|free money|free SEO|for free|fund|golden|help grow|here to help|hi there|honey|imagine having|increase your|instant|introduce you|landscape|leaverage|lifetime|loan|marketing|no oblig|pay off|personalized|porn|promote your|prove|rank on|return on their|SEO |sexy|staggering|subscribers|tax credit|team |to learn|top-|trusted|in charge|uncover|unparalleled|viagra|viewers|we guaran|working capital|you tired/i',$comments)) { $error_message .= "There are spammy words in the Message.<br />"; } // 优化原有大写字母检测:仅拦截连续3个大写字母后还有其他字符的情况,避免误拦合法缩写 if(preg_match('/[A-Z]{3}[A-Za-z0-9]+/m',$comments)) { $error_message .= "Weird CAPs in the Message.<br />"; } if(preg_match('/[A-Z]{3}[A-Za-z0-9]+/m',$name)) { $error_message .= "Too many capitals in the Name.<br />"; } // 原有Name字段垃圾特征检测 if(preg_match('/http|www/i',$name)) { $error_message .= "No Spam.<br />"; } // 原有手机号格式验证 if(!preg_match('/^[0-9]{10,}$/', $telephone)) { $error_message .= "Phone requires 10 numbers.<br />"; } // 错误信息触发拦截 if(strlen($error_message) > 0) { died($error_message); } ?>
关键逻辑说明
- 合法缩写兼容:通过
$allowed_acronyms列表维护允许的全大写缩写,避免误拦这类合法内容 - 单个无意义词拦截:用
^\w+$判断是否为单个词,再对比合法缩写列表,不在列表中则触发拦截 - 无空格连写拦截:正则
(?:[a-z]+[A-Z]*[a-z]*){3,}匹配至少3组含小写字母的连续块,[A-Za-z]{10,}拦截过长的无空格纯字母字符串,精准覆盖垃圾信息的随机字母组合场景 - 原有大写检测优化:修改正则为
[A-Z]{3}[A-Za-z0-9]+,仅拦截连续3个大写字母后还有其他字符的情况,避免误拦3个字母的合法缩写
内容的提问来源于stack exchange,提问作者HWL1223
相关产品推荐
相关产品推荐

