简体   繁体   中英

Issue filtering words in contact form PHP based

I having a issue filtering bad words inside a contact form message. It strips all the message except the first letter of the word. Any help?

below is just getting the info

<?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']);

this is the function I am trying to use to strip the bad words and replace them

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

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

checks the drop down options and doesn't allow certain subjects to be emailed.

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;
}

places the info and sends

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

?>

You could use str_replace since it can take array.

For instance:

$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);

Results would be: Hello there my good friends! I am very happy to see you all today even though I feel like *.

Why re-invent new methods when PHP already offers plenty of useful ones? This should be enough to remove "bad words" from messages being sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM