check if value is in array
This is probably v.easy but my ph开发者_StackOverflow社区p is very rusty. I need to implement a bad word filter...I currently have this:
if(!in_array($_POST['Name'],$profanities)) { echo $row['Name']; }
...and an profanities array with bad words in it. Problem is I want to be able to check if any portion of the name the user has entered contains one of those bad words....what I've currently got only checks if the name is the exact bad word....how do i do this?
thanks
Technically there are a few options, and some other answers point these out. Realistically, however, I would say do not do this.
Profanity filters are notoriously frustrating and limiting for users with unusual or foreign names/address/etc.
Please see: http://en.wikipedia.org/wiki/Swear_filter#Unintended_consequences
Additionally, if your users want to find a way around the filter, they will. They'll use similar sounding characters or special characters as both substitutions and additions.
EDIT: There is an excellent stackoverflow question already addressing this issue. please see How do you implement a good profanity filter?
EDIT: although the above stackoverflow question refers to Jeff's post about this, it can't hurt to repeat and reinforce. Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?
$name = $_POST['Name'];
foreach($profanities as $profanity) {
if (preg_match('/\w' . preg_quote($profanity, '/') . '\w/i', $name) {
// Bad word on its own
}
}
This will match a bad word on its own only... i.e. it will match bad
in Is it bad?
but not in baddy
. You can remove the word boundaries if you want to match that, or perhaps try strstr()
.
However, a valid name may contain a substring that is considered bad if you decide to check for simple string matching.
What if I wanted to name my username after my hometown?
This code will match all bad words found by searching a case-insensative match.
foreach($profanities as $profanity)
{
if(preg_match('/' . $profanity . '/i', $row['Name']))
{
echo 'Bad word found!';
}
}
精彩评论