I wrote a short function that should check if user input does contain any bad words that I predefined inside $bad_words array. I don't even care to replace them - I just want to ban if there are any. The code seems to work as it should - in the example below will detect the quoted string badword and the function does return true.
My question: Is this a good way to use foreach and strpos()? Perhaps there is better way to check if $input contains one of the $bad_words array elements? Or is it just fine as I wrote it?
function checkswearing($input)
{
$input = preg_replace('/[^0-9^A-Z^a-z^-^ ]/', '', $input);//clean, temporary $input that just contains pure text and numbers
$bad_words = array('badword', 'reallybadword', 'some other bad words');//bad words array
foreach($bad_words as $bad_word)
{//so here I'm using a foreach loop with strpos() to check if $input contains one of the bad words or not
if (strpos($input, $bad_word) !== false)
return true;//if there is one - no reason to check further bad words
}
return false;//$input is clean!
}
$input = 'some input text, might contain a "badword" and I\'d like to check if it does or not';
if (checkswearing($input))
echo 'Oh dear, my ears!';
else
{
echo 'You are so polite, so let\'s proceed with the rest of the code!';
(...)
}