Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Detecting and replacing bad words in PHP

David Carr

PHP & MySQL Tutorials

  • Putting it all together:
  • 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];
    }
    ?>

     

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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