我需要在注册过程中禁用某些单词


I need to disallow certain words in my registration process

if (strtolower(strpos($_POST['username']), "host") !== FALSE) {
                    $errors[] = 'You cannot have the word HOST in your name.';
                }

现在这是完美的,如果我想阻止某人使用名称Host Andy,例如,但如果有人创建用户名Ghost和类似的…我如何过滤它,只阻止第一个单词是host?

编辑:

    if (strtolower(strpos($_POST['username']), "host") === 0) {
    $errors[] = 'You cannot have the word HOST in your name.';
    }

您可以使用preg_match根据边界检查单词:

$pattern = "/'bhost'b/i";
if(preg_match($pattern, $_POST['username']))
{
    $errors[] = 'You cannot have the word HOST in your name.';
}

编辑

若要只匹配第一个单词,只需删除第一个单词边界:

$pattern = "/^host'b/i";

进一步编辑:添加^字符以单词host开始字符串。它告诉regex它必须以host作为单个单词开始,不区分大小写。

如果您想要停止以"host%"开头的用户名,然后执行:

if (substr(ltrim(strtolower($_POST["username"])),0,4)=="host") {
   $errors[] = 'You cannot have the -starting- word HOST in your name.';
}

更新:

我添加了ltrim只是为了让事情更安全,防止更多的讨厌的方法;
当您通过"host"案例时,可以随意删除它并处理修剪。

最后,虽然不清楚,如果你想停止"host",但允许"host "(?),只需更改:

if (substr(ltrim(strtolower($_POST["username"])),0,5)=="host ") {

如果host(即host后跟空格)位于字符串的开头,则stripos($_POST['username'], "host ") === 0为真,否则为假。

如果第一个单词前可以有空格,您可能需要先使用http://www.php.net/manual/en/function.ltrim.php。

如果host前面有符号,或者host后面有符号,在字符串的开始也需要被禁止,请告诉我

虽然,我想问为什么Host需要从用户名开始被禁止。能不能用另一种方式来表示?例如,如果只有主机使用绿色斜体的名称,则不可能欺骗主机。

这是我在我的网站上用来过滤坏词的方法。根据你的喜好来使用它。它会给你指明正确的方向,因为它只会过滤"iamabadword"而不会过滤"iamabadword"。

function filterBadWords($str) {
    $badWordsFile = "badwords.txt";
    $badFlag = 0;
    if(!is_file($badWordsFile)) {
        echo "ERROR: file missing: ".$badWordsFile;
        exit;
    }
    else {
        $badWordsFH = fopen($badWordsFile,"r");
        $badWordsArray = explode("'n", fread($badWordsFH, filesize($badWordsFile)));
        fclose($badWordsFH);
    }
    foreach ($badWordsArray as $badWord) {
        if(!$badWord) continue;
        else {
            $regexp = "/'b".$badWord."'b/i";
            $badword_add_last_letter = $badWord.substr($badWord, -1);
            $regexp_add_last_letter = "/'b".$badword_add_last_letter."'b/i";
            if(preg_match($regexp,$str)) $badFlag = 1;
            if(preg_match($regexp_add_last_letter,$str)) $badFlag = 1;
        }
    }
    if(preg_match("/'[url/",$str)) $badFlag = 1;
    return $badFlag;
}

文件badwords。txt就是这样一个文件

badword1
badword2
badword3
编辑:

如果你只想要HOST这个词,那么使用这个函数:

function filterString($str) {
    if(preg_match("/'bhost'b/i",$str)) return true;
    return false;
}