I have a form in which I want to allow only text and number fields: my input filter will not allow $%^&*()_
.
I wrote the following code:
<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>
and this works well.
My problem is that I need to filter bad words and save the input text to a database. I wrote following code to save to a database:
<?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,))
?>
I am using the above code to save the text to the database, but BAD WORD FILTER dosen't works it saves input as user enters bad_word_filter does't works
i.e. the field is created in the database and filter word is saved. i don't want filter word to be saved to SQL
Could some one please help me? Thanks.
I couldn't fix your present code (as much as I tried), but am submitting the following suggestive method, using 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;
Edit:
$input = 'sE x';
$filtered_list = array(
'sex',
'sE x',
'SEX',
);
$replaced = 'beep';
$filtered = str_replace($filtered_list, $replaced, $input);
echo $filtered;