PHP Content Filter: Replace Bad Words


In this tutorial we will create a basic word filter that can be used to remove any bad words a user may use on your website.

So let's begin with the SQL query.
Run this is phpMyAdmin
SQL Query
  1. CREATE TABLE `filter` (
  2. `word` varchar(50) NOT NULL,
  3. PRIMARY KEY (`word`)
  4. ) ENGINE=MyISAM;


This table will hold all the words that shouldn't be used on your website.
I'm sure you can think of loads of words you can put in this table so I will not be listing any.

Now let's get to work with the filter
filter.php
  1. <?php
  2.  
  3. // Create a global connection variable
  4. $connection = new mysqli("localhost", "username", "password", "database"); // Replace with your DB credentials
  5.  
  6. // Check for connection errors
  7. if ($connection->connect_error) {
  8. die("Database connection failed: " . $connection->connect_error);
  9. }
  10.  
  11. // Create a function to filter bad words
  12. function filter($content) {
  13. global $connection; // Access the global connection variable
  14.  
  15. // Prepare and execute the query to fetch all words from the `filter` table
  16. $query = "SELECT word FROM filter";
  17. $result = $connection->query($query);
  18.  
  19. // Check if the query returned any rows
  20. if ($result->num_rows > 0) {
  21. // Loop through the rows and replace bad words with "(BadWord)"
  22. while ($row = $result->fetch_assoc()) {
  23. $content = str_replace($row['word'], "(BadWord)", $content);
  24. }
  25. }
  26.  
  27. // Free the result set
  28. $result->free();
  29.  
  30. // Return the "safe" content
  31. return $content;
  32. }
  33.  
  34. // Close the database connection
  35. $connection->close();
  36. ?>



To use this filter you need to include the filter.php file into your script, like in the example below.
PHP Code
  1. include("filter.php");


Then to use the filter, you simple need to run the filter() function we created.
PHP Code
  1. // Example usage
  2. $content = "This is a example text."; // Example content
  3. echo filter($content); // Apply the filter function
  4.  
  5. // Output (if "example" is in the table as a "bad word"
  6. // This is a (BadWord) text.


Change the variables above to what you want to filter on your site.
DanielXP's Avatar
Author:
Views:
2,743
Rating:
Posted on Sunday 22nd June 2014 at 03:55 AM
DanielXP
DanielXP's Avatar
I have updated this tutorial.

@SkillMaster, its a tutorial to be used on any system, you can replace the "DBconnect.php" used in the example for what file you need.
Posted on Thursday 21st June 2007 at 08:17 PM
SkillMaster
SkillMaster's Avatar
ya and you would include config.php not DBconnect.php?
Posted on Thursday 21st June 2007 at 04:40 PM
DanielXP
DanielXP's Avatar
In the database. You add the word in a new row.
Posted on Thursday 21st June 2007 at 04:14 PM
new2old
new2old's Avatar
So where do you add the words?
I am really confused