Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Detecting and replacing bad words in PHP

David Carr

Tutorials PHP & MySQL

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

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.