



(2 ratings)
In this tutorial you’ll learn how to censor the swear words and profanity on your website.
You could even use this tutorial to prevent people making posts about your competitors.
* Contains strong language *
First things first, the functions we will be using in this tutorial.
The nice things about this tutorial are that it will teach you how to load a file as an array using the file() function, it will also cache that file using global to see if the censored words have already been loaded and it will replace them with their counterpart (word for example as either w***d or *****, both 5 letters).
To start things out, were going to create a file with the swearwords.
Alternitavely, you could create a string, but we’ll talk about that later.
swearwords.txt
shit
bitch
arkinex
then, the php part of the censoring.
/* arkinex-censor.php v1.0 - www.arkinex.com */
/* don't forget to create swearwords.txt */
function censor($string,$all=false) {
// Global checks the cache to see if $censor_words already exists.
global $censor_words;
// If there is no cache aka censor_words is empty or is not an array
// Then load the swearwords.txt
if (empty($censor_words)||!is_array($censor_words)) {
$censor_words = Array();
$censor_words = @file('swearwords.txt');
}
$censors = Array();
// Check if the censor words are empty.
// Returns an invisible error and the string if they are.
if (empty($censor_words)) return '<!--error-->'.$string;
// This foreach loops through each censor word
foreach ($censor_words as $word) {
// This checks if you want all the word censored or partial
// Str_repeat repeats * for the number of letters (minus 2)
// Substr grabs the first and last letter (the 2)
if (!$all) $censors[] = substr($word,0,1).str_repeat('*',
strlen($word)-2).substr($word,-1);
// If you want to censor the full word..
// It Str_repeats for the length of the entire word
else $censors[] = str_repeat('*', strlen($word));
}
// Str_replace replaces all the words with their censors
$string = str_replace($censor_words, $censors, $string);
// This returns the string for display
return $string;
}
echo censor("The cat sat on the arkinex",true);
// Outputs: The cat sat on the a*****x
Now to the example:
echo censor("The cat sat on the arkinex");
// Outputs: The cat sat on the a*****x
echo censor("You should all go to arkinex!", true);
// Outputs: You should all go to *******!
You can download the full snippet, swearword-censor.phps.
Reply to this article if you need additional help or have any idea’s.
20 Random Tutorials from the same category :
PHP Thumbnail Generation Script
Intro To Object: Option Variables
Dynamic PHP Google Sitemap
RSS Feed from a MySQL Database
Advanced Navigation using Includes
Building a Subscribe/Unsubscribe App in PHP with Dreamweaver CS3
Sending SMS with PHP
Hide .php extension with url rewriting using .htaccess
Random Password Generation
Simple swear filter tutorial













