如何解决PHP strpos() 作为实现脏话过滤器的一种方式
我编写了一个简短的函数来检查用户输入是否包含我在 $bad_words
数组中预定义的任何坏词。我什至不在乎更换它们 - 我只想禁止,如果有的话。代码似乎可以正常工作 - 在下面的示例中将检测带引号的字符串 badword
并且函数确实返回 true
。
我的问题:这是使用 foreach
和 strpos()
的好方法吗?也许有更好的方法来检查 $input
是否包含 $bad_words
数组元素之一?还是像我写的一样好?
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!';
(...)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。