首页 > 解决方案 > PHP strpos() 作为一种实现脏话过滤器的方法

问题描述

我写了一个简短的函数来检查用户输入是否包含我在$bad_words数组中预定义的任何坏词。我什至不在乎更换它们 - 如果有的话,我只想禁止。该代码似乎可以正常工作 - 在下面的示例中将检测带引号的字符串badword并且该函数确实返回true

我的问题:这是使用foreachand的好方法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!';
    (...)
}

标签: phparraysstringforeachstrpos

解决方案


推荐阅读