【问题标题】:Issue filtering words in contact form PHP based在基于 PHP 的联系表单中发出过滤词
【发布时间】:2012-05-03 14:40:33
【问题描述】:

我在过滤联系表单消息中的坏词时遇到问题。 它会删除除单词首字母之外的所有消息。 有什么帮助吗?

下面只是获取信息

<?php
$error = '';
if(!empty($_POST['username'])) $username = $_POST['username'];
if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['subject'])) $subject = check($_POST['subject']);
if(!empty($_POST['message'])) $msg = filter($_POST['message']);

这是我试图用来去除坏词并替换它们的函数

$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',);

 function filter($matches) {
 global $bad_words;
 $replace = $bad_words[$matches[0]];
 return !empty($replace) ? $replace : $matches[0];
 }

检查下拉选项并且不允许通过电子邮件发送某些主题。

function check($str){
global $error;
if ($str == 'Mean Spirited Comment'){
  $error = 'You sent a Mean-Spirited Comment';
} else if ($str =='Political Comment'){
  $error = 'You sent a Political Comment';
}
 return $str;
}

放置信息并发送

$to = 'email@email.com';
 if (!empty($subject) && !empty($msg) && !empty($email) && !empty($username)){
if ($error == ''){
  mail($to, $subject, $msg, 'From:' . $email);
} else {
  print $error;
}
}

?>

【问题讨论】:

  • 不是答案,但您应该使用isset() 而不是empty()。也请不要使用globals。

标签: php html function filter contact


【解决方案1】:

你可以使用 str_replace,因为它可以使用数组。

例如:

$message = "Hello there my good friends! I am very happy to see you all today even though I feel like crap.";
$badWords = array("Crap", "Damnit", "Frack");
echo str_replace($badWords, "*", $message);

结果将是:你好,我的好朋友们!今天很高兴见到大家,尽管我感觉很*。

既然 PHP 已经提供了大量有用的方法,为什么还要重新发明新方法?这应该足以从正在发送的消息中删除“坏词”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多