错误过滤输入中的坏词并保存到 SQL


ERROR filter bad words in input and saving to SQL

>我有一个表单,我只想允许文本和数字字段:我的输入过滤器不允许$%^&*()_

我写了以下代码:

输入滤波器

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
        <form class="form-horizontal" method="post" action="for.php" enctype="multipart/form-data">
            <input id="textinput" name="name" type="text" placeholder="Sanoj Lawrence" class="form-control input-md" onkeyup="validate();">
            <input type="submit" class="btn btn-success">
        </form>
        <script>
            $(function() {//<-- wrapped here
                $('.form-control').on('input', function() {
                    this.value = this.value.replace(/[^a-zA-Z0-9@ ]/g, ''); //<-- replace all other than given set of values
                });
            });
        </script>

这很有效。

我的问题是我需要过滤坏词并将输入文本保存到数据库中。我编写了以下代码以保存到数据库:

表单处理代码

<?php
$text = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$text = preg_replace_callback('!'w+!', 'filter_bad_words', $text);
echo $text;
$bad_words = array(
    'word1' => 'se x',
    'word2' => 'SEX',
    'word1' => 's e x',
    'word1' => 's E x',
    'word1' => 'se X',
);
function filter_bad_words($matches) {
    global $bad_words;
    $replace = $bad_words[$matches[0]];
    return isset($replace) ? $replace : $matches[0];
}
$db_password = '123456';
$db_username = 'sanoj';
$conn = new PDO('mysql:host=localhost;dbname=localtest', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('INSERT INTO filter (cat) VALUES (:cat)');
$data->execute(array(':cat' => $text,))
?>

我正在使用上面的代码将文本保存到数据库中,但是坏词过滤器不起作用,它会在用户输入时保存输入bad_word_filter does't works即在数据库中创建字段并保存过滤词。 我不希望将过滤器词保存到SQL

有人可以帮我吗?谢谢。

我无法修复您当前的代码(尽管我尝试了很多(,但是使用str_replace()提交以下建议性方法:

$string = $_POST['name'];
$words = array('se x', 'SEX', 's e x');
$replacements = array('censored 1', 'censored 2', 'censored 3');
$result = str_replace($words, $replacements, $string);
echo $result;

编辑:

$input = 'sE x';
$filtered_list = array(
    'sex',
    'sE x',
    'SEX',
);
$replaced = 'beep';
$filtered = str_replace($filtered_list, $replaced, $input);
echo $filtered;