【发布时间】:2014-06-26 20:11:32
【问题描述】:
我有一个将 name 和 comment 保存到 MySQL 数据库的 html 表单。 name 和 comment 条目随后以表格格式显示在 php 页面上。
我想让评论字段中的任何脏话在 PHP 输出表中显示为 三个星号。
我让它按如下方式工作:
swear.php
<?php
$find = array("BadWord1","BadWord2","BadWord3"); //words I don't want displayed
$replace = array("***","***","***"); //The replacements
?>
process.php
<?php
//connect to the database
$dbc = mysqli_connect('host', 'username', 'password', 'db') or die('Error connecting to MySQL server.');
//connect to swear.php
require("swear filter.php");
//process the form & email
$name = mysqli_real_escape_string($dbc, trim($_POST['name']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$comment= mysqli_real_escape_string($dbc, trim($_POST['comment']));
$comment=str_replace($find, $replace, $comment);
$from = 'From: whoever';
$to = 'anemail@something.com';
$subject = 'Hello';
$human = mysqli_real_escape_string($dbc, $_POST['human']);
$body = "From: $name\n E-Mail: $email\n Message:\n $comment";
if(isset($_POST['submit'])){
if ($name != '' && $email != '') {
if ($human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<h1 class=\"meantime\"></h1>';
} else {
echo '<h1 class=\"meantime\">Something went wrong, go back and try again!</h1>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<h1 class=\"incorrect\">You answered the anti-spam question incorrectly!</h1>';
}
} else {
echo '<h1 class=\"required\">You need to fill in all required fields!!</h1>';
}
}
?>
<?php
//connect to the database
$dbc = mysqli_connect('host', 'username', 'password', 'db') or die('Error connecting to MySQL server.');
//create the insert statement
$query = "INSERT INTO table(name, email, comment, date) VALUES ('$name', '$email', '$comment', now())";
//insert record into the table
$result = mysqli_query($dbc, $query) or die ('Error querying database.');
//close connection to database
mysqli_close($dbc);
//display thank you to user and link back to form page
print "<br>";
print "<h2 class=\"meantime\">Nice 1 <span class=\"nice\"> " . stripslashes($name) . "</span>. I shall check it out.</h1>";
print "<h3 class=\"meantime\">In the meantime, see what others have posted.</h3>";
print "<br><br>";
print "<h3 class=\"meantime\"><a href=\"comments.php\"><span class=\"underline\">Comments so far</span></a></h3>";
print "<br><br>";
?>
有没有更有效的方法来完成 swear.php 文件。
- 我是否必须为每个替换的坏词键入 三个星号 - 因为它一直都是一样的?
有没有更好的方法来实现一个简单的脏话过滤器?
感谢您的帮助,安迪 ;-)
【问题讨论】:
-
$comment=str_replace($find, '***', $comment); -
@dave 那行不通......你会替换各种不应该替换的东西。
-
@Brad 又名“斯肯索普问题”