PHP & MySQL | Tutorials

David Carr

Detecting and replacing bad words in PHP

User submitted content should always be moderated before its used or outputted on a public website, any system however sophisticated won't be able to understand contexts of words.

Having said that here's a simple way to detect words in a string that can be detected with php and removed or replaced with another word.

First a sample string

$text = 'A sample string that contains words you would rather replace.';

Echo the string and pass each word to a custom function called filter_bad_words by using a callback and replace function built into php: preg_replace_callback

echo preg_replace_callback('!w+!', 'filter_bad_words', $text);

Inside the function create an array or words and their counterpart to replace this would by a blank string or a word, symbol etc.

Each word will be search if there is a match the item in the array will be used and replace the matching word.

function filter_bad_words($matches) {
  
  $bad_words = array(
    'replace' => '[censored]',
    'words' => '[censored]'
  );
 
  $replace = $bad_words[$matches[0]];
  return isset($replace) ? $replace : $matches[0];
}

Putting it all together:

<?php
$text = 'A sample string that contains words you would rather replace.';

echo preg_replace_callback('!w+!', 'filter_bad_words', $text);
 
function filter_bad_words($matches) {
  
  $bad_words = array(
    'replace' => '[censored]',
    'words' => '[censored]'
  );
 
  $replace = $bad_words[$matches[0]];
  return isset($replace) ? $replace : $matches[0];
}
?>

 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.