i am building a system in which user comment and earn credit. to get credit quickly user add comment such as "fffff" , "niceeeeeeeeee", "greeeeeeaaaatt", "aaaa", "b" etc...
Is there anyway to filter out these comments. any suggestion will be appreciated.
You could check to see if the user's input contains 3 consecutive characters using a regular expression (since I'm not aware of any words in english which have 3 of the same letter in a row)
$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!";
}
This would match "niceee", "greeeat", "aaaa" etc. or any string with the same letter 3 or more times in a row. If you want to check users' input against multiple patterns, you could put your regular expressions in an array and check them all e.g.:
$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";
}
}
Or if you don't have too many patterns (and you aren't concerned with readability) you could just concatenate all the patterns together with |
.
if (preg_match("/(.)\\1\\1|^.$|.{15,}|([A-Za-z]{2,})\\2\\2/", $user_input)) {
echo "This is an invalid string";
}
In order to test correct spelling, you could use pspell_check() function.
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, "niceeeeeeeeee")) {
echo "Correct spelling.";
} else {
echo "Wrong spelling";
}