php - PHP strpos() 作为一种实现脏话过滤器的方法
问题描述
我写了一个简短的函数来检查用户输入是否包含我在$bad_words
数组中预定义的任何坏词。我什至不在乎更换它们 - 如果有的话,我只想禁止。该代码似乎可以正常工作 - 在下面的示例中将检测带引号的字符串badword
并且该函数确实返回true
。
我的问题:这是使用foreach
and的好方法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!';
(...)
}
解决方案
推荐阅读
- reactjs - 当我发送发布请求时,Django Rest Framework 被禁止
- c# - C# 应用程序无法加载嵌入的文本资源
- excel - 在 Excel 中,如何通过匹配 d 列和 h 列中的名称(不按顺序)从 c 列返回不同名称的列表,并且不带空格列出?
- visual-studio-code - VScode 中的系统环境变量
- node.js - 管理员删除用户的节点功能代码不起作用
- python - 我是编码新手,我正在学习 python,我写了一些代码,但是有一个函数永远无法工作,原因对我来说不是那么明显
- discord.js - 斜杠命令处理程序中的 Discord.js v13 TypeError
- python - Python Selenium:如何从具有相同相对xpath的多个未定义长度的html列表中获取元素?
- javascript - Javascript:如何使用变量初始化音频文件
- java - 如何在我输入的两个数字之间打印数字?