不确定strpos()是否是正确的函数

时间:2015-04-06 15:43:37

标签: php

我不确定strpos()是否适合用于此目的 任务。

问题:

如果用户在我的垃圾邮件变量中输入仇恨或其他字符串 它返回正确的垃圾邮件过滤器消息,但如果是用户 输入垃圾邮件变量与任何不在其中的字符串混合 通过处理。

我希望输入从第一个字符串检查到最后一个字符串 并且那个t不包含任何垃圾邮件变量字符串 返回过程,这是我的代码

<?php
    //messgae
    error_reporting(E_ALL ^ E_NOTICE);
    $msg = array(); 
    $spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
    $spam_array = explode(" ",$spam);

    $check = strpos($spam, $_POST['message']);

         if ($check == true) {
        //do nothing
        $msg['invalid'] =  'Spam filter test didnt allow your message';

       } else {

        $msg['valid'] = 'process';   
       }


    if(isset($_POST['send'])){

      $message= $_POST['message']; 
    }

     ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Strpos</title>
    </head>

    <body>
    <?php 
    if (isset($msg)) {
    echo '<ul>';
    foreach ($msg as $alert) {
    echo "<li class='warning'>$alert</li>\n";
    }
    echo '</ul>';
    }?>
    <form action="" method="post">
    <input name="message" type="text" />
    <input name="send" type="submit" value="Submit" id="send" />
    </form>
    </body>
    </html>

2 个答案:

答案 0 :(得分:1)

你用$spam_array在那里开始了。 他们检查它,你检查你的消息中是否找到了确切的坏词。

同时stripos代替strpos,以便它不区分大小写。

$spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
$spam_array = explode(" ",$spam);
$isSpam = isSpam($_POST['message'], $spam_array);


function isSpam($content, $spamList)
{
    foreach($spamList as $badWord) {
        if(stripos($content, $badWord) !== false) {
            return true;
        }
    }

    return false;
}

答案 1 :(得分:0)

您需要使用字边界来改进您的支票,否则您会对像&#34;手套&#34;等字词产生误报。 (爱)和&#34; Essex&#34; (性别)。您还应该使其不区分大小写。

以下方法(check函数)在查找每个&#34;垃圾邮件字时使用带有字边界元字符的preg_match&#34;在消息中。 i修饰符也使其不区分大小写:

function check($msg, $spam_array) {
    foreach ($spam_array as $spam_word) {
        if (preg_match("/\b" . $spam_word ."\b/i", $msg)) {
            return false;
        }
    }
    return true;
}

function test($msg, $spam_array) {
    echo "$msg => ", check($msg, $spam_array) ? 'OK' : 'not OK', PHP_EOL;
}

$spam = "hate partisan party kill maim murder violence love sex fight beat "
    . "assasinate thug steal sell bribe protest baricade bullets militia fear";
$spam_array = explode(" ", $spam);

test("I'm known for my cookie munching skills.", $spam_array);
test("I could kill for some cookies right now!", $spam_array);

输出:

I'm known for my cookie munching skills. => OK
I could kill for some cookies right now! => not OK