Tutorials, PHP & MySQL

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

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.