strpos() == true 不能可靠地给出正确的结果[重复]

问题描述 投票:0回答:2

不确定

strpos()
是否是用于此目的的正确函数 任务。

问题:

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

我希望输入从第一个字符串到最后一个字符串进行检查 并且 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>
php strpos
2个回答
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;
}

0
投票

您需要改进对单词边界的检查,否则您会对“手套”(爱)和“埃塞克斯”(性)等单词产生误报。您还应该使其不区分大小写。

以下方法(

check
函数)在查找消息中的每个“垃圾邮件单词”时,使用带有单词边界元字符的preg_match
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
© www.soinside.com 2019 - 2024. All rights reserved.