我正在构建一个系统,在这个系统中,用户可以发表评论并获得积分。为了快速获得信用,用户添加评论,如"fffff"、"niceeeeeeeeee"、"greeeeeaaatt"、"aaaa"、"b"等。
是否有过滤掉这些评论的方法。任何建议都将不胜感激。
您可以使用正则表达式检查用户的输入是否包含3个连续字符(因为我不知道英语中有任何单词在一行中包含3个相同的字母)
$user_input = "niceeeeeeeeeeee";
if (preg_match("/([A-Za-z])\1\1/", $user_input)) {
echo "String contains the same letter 3 times in a row and is not valid";
} else {
echo "String is ok!";
}
这将匹配"niceee"、"greeat"、"aaaa"等或任何连续3次或更多次具有相同字母的字符串。如果你想根据多种模式检查用户的输入,你可以把正则表达式放在一个数组中,然后全部检查,例如:
$patterns = [
"/(.)\1\1/", // any character (not just letters) 3+ times in a row
"/^.$/", // a single character
"/.{15,}/", // contains a word longer than 15 characters
"/([A-Za-z]{2,})\1\1/" // 2 letters alternating e.g. "abababab"
];
foreach( $patterns as $pattern ){
if (preg_match($pattern, $user_input)) {
echo "This is an invalid string";
}
}
或者,如果您没有太多的模式(并且不关心可读性),您可以将所有模式与|
连接在一起。
if (preg_match("/(.)\1\1|^.$|.{15,}|([A-Za-z]{2,})\2\2/", $user_input)) {
echo "This is an invalid string";
}
为了测试拼写是否正确,可以使用pspell_check()函数。
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, "niceeeeeeeeee")) {
echo "Correct spelling.";
} else {
echo "Wrong spelling";
}