Detecting and replacing bad words in PHP

David Carr

1 min read - 4th Jun, 2013

Table of Contents

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

 

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.