Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    New Coder
    Join Date
    Mar 2008
    Posts
    34
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Super Simple Bad Word Filter

    So you're a newbie at coding? You need someone to talk to you in plain english and tell you step by step by step how to do something like: Filter bad words.

    Here you go!

    Step 1:

    Create a new web page in your file manager or with a text editor. Paste the following code into it:
    Code:
    <? function ReplaceBadWords($str, $bad_words, $replace_str){
        if (!is_array($bad_words)){ $bad_words = explode(',', $bad_words); }
        for ($x=0; $x < count($bad_words); $x++){
            $fix = isset($bad_words[$x]) ? $bad_words[$x] : '';
            $_replace_str = $replace_str;
            if (strlen($replace_str)==1){ 
                $_replace_str = str_pad($_replace_str, strlen($fix), $replace_str);
            }
            $str = preg_replace('/'.$fix.'/i', $_replace_str, $str);
        }
        return $str;
    }
    ?>
    Then save this new file as filter.php

    STEP 2:

    Then, go to the web page where you want to to filter the bad words.

    Let's say you want to filter the bad words in your comments section. Let's say your comments are called by $comments. Then you would wrap the following code around $comments and any bad words that you specify will be filtered. For example, this is how a very simple page would look:
    Code:
    include ("filter.php");
    $str = <<<EOF
    $comments
    EOF;
    // bad words:
    $replace_str = "@#$*!";
    $bad_words = array('****','****','****','sucks','suck');
    print ReplaceBadWords($str, $bad_words, $replace_str);
    As you can see, at the beginning you have "include ("filter.php"); <--- this does exactly what it says, it includes the file you created in step 1 that you saved as filter.php.

    The rest is what makes it work to make a long story short. Where is says "$comments" in the code above this is where your comments on your page go. You can also just type in some sentences to test it.

    $replace_str = "@#$*!"; <----- that's what the bad words are going to look like when we're finished with 'em!

    $bad_words = array('bad1','bad2','bad3','bad4','bad5'); <---- that's where you put the words you want to block.


    THE END.

    Now this is a very simple version compaired to many complex versions out there. But, it is very simple to install.
    Just paste this:
    include ("filter.php");
    $str = <<<EOF
    AND PUT ANY CONTENT YOU WANT HERE AND IT WILL BE FILTERED
    EOF;
    // bad words:
    $replace_str = "@#$*!";
    $bad_words = array('bad1','bad2','bad3','bad4','bad5');
    print ReplaceBadWords($str, $bad_words, $replace_str);


    Is it full proof? no. Can rude people work around it and still post mean things? yes. Does it help make it harder for people to leave rude messages? yes. Every little bit helps.


    I'm sure some of the experienced coders here might see this code and have better methods, but, no one would really help me here at these forums so I had to figure it out myself.

  • #2
    Regular Coder
    Join Date
    Mar 2008
    Posts
    103
    Thanks
    1
    Thanked 8 Times in 8 Posts
    Isn't this just a WAY more complicated way of what I did? commented version below.
    PHP Code:
    <?php
    $words 
    = array("bad1""bad2""bad3"); // bad words
    $replacement = array("@#$@#""good2""b***3"); //however you want to censor 
    $string $_POST['string']; // inputed string
    $cleanstring str_ireplace($words$replacement"$string"); //clean it up changed to ireplace removing case sensitivity.
    echo("$cleanstring"); //echo it out.
    ?>
    Last edited by p4plus2; 03-24-2008 at 06:13 AM.

  • #3
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Quote Originally Posted by p4plus2 View Post
    Isn't this just a WAY more complicated way of what I did? commented version below.
    PHP Code:
    <?php
    $words 
    = array("bad1""bad2""bad3"); // bad words
    $replacement = array("@#$@#""good2""b***3"); //however you want to censor 
    $string $_POST['string']; // inputed string
    $cleanstring str_ireplace($words"$replacement""$string"); //clean it up changed to ireplace removing case sensitivity.
    echo("$cleanstring"); //echo it out.
    ?>
    You're casting the array in $replacement as a string, which will end up not working.

  • #4
    Regular Coder
    Join Date
    Mar 2008
    Posts
    103
    Thanks
    1
    Thanked 8 Times in 8 Posts
    whoops my bad I accidently added quotes. >.< typed little to fast should just have quotes on the string variable

  • #5
    Senior Coder Len Whistler's Avatar
    Join Date
    Jul 2002
    Location
    Vancouver, BC Canada
    Posts
    1,323
    Thanks
    26
    Thanked 100 Times in 100 Posts
    Another useful feature to add to a bad word filter is to block them from your site temporarily if they abuse your comment/forum page.

    Once they submit a "bad" word their IP is entered into a database - MySQL or TXT file - and at the same time they are directed to an alternate site - yahoo.com, google.com - using the php header function.
    PHP Code:
    <?php
    (header('Location: http://www.google.com');
    ?>
    If they try and get back to your site and their IP matches any IP address in the database they are then sent back to the alternate site, again with the php header function. After a set amount of time the IP address is deleted from the database giving site access to the offender.
    Leonard Whistler

  • #6
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Len Whistler View Post
    are directed to an alternate site - yahoo.com, google.com - using the php header function.
    PHP Code:
    <?php
    (header('Location: http://www.google.com');
    ?>
    I'm sorry but yahoo, google are search engine, public service, not garbage collectors.
    I don't like if somebody redirect any idiot to my domain.
    The idea is not bad, the url is,
    A alternative to that, I don't know how it work with php and header since I use it in .htaccess, is to redirect to "-".

    best regards

  • #7
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    I don't think Yahoo, or Google would mind since both encourage users to set them as the user's homepage.

  • #8
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Inigoesdr View Post
    I don't think Yahoo, or Google would mind since both encourage users to set them as the user's homepage.
    is not the same thing. In first case is an accident, later is a stable client you want/need. Google and Yahoo have, along with their specific problems, the same problems like any other bussines on the net.

    best regards

  • #9
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    Quote Originally Posted by oesxyl View Post
    is not the same thing. In first case is an accident, later is a stable client you want/need. Google and Yahoo have, along with their specific problems, the same problems like any other bussines on the net.

    best regards
    I have to be honest and say I don't know what you're talking about. The example given above was that the user was banned, in which case you wouldn't want them on your site necessarily. It would be more user-friendly to show a message, yes, but if they're banned they probably already know they did something wrong.

  • #10
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Inigoesdr View Post
    I have to be honest and say I don't know what you're talking about.
    what is the pourpuse of having a site? => comunicate and/or make bussines.
    google and yahoo make bussines on the net.
    what profit gain a site when a user is redirected there and same user after less then 30 seconds go to other site?
    what useless costs you have because somebody redirect users to your site? Keep in mind that we talking about google or yahoo, and about this specific case.
    don't say that costs does not matter or are less because are a lot of indirect costs and in this case could be easy avoided.

    The example given above was that the user was banned, in which case you wouldn't want them on your site necessarily.
    not banned, redirected to another site, is something else and is clear not the same thing

    It would be more user-friendly to show a message, yes, but if they're banned they probably already know they did something wrong.
    , in this case user-friendly solution implies to be very understanding with users behavior,

    best regards

  • #11
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    Quote Originally Posted by oesxyl View Post
    what is the pourpuse of having a site? => comunicate and/or make bussines.
    google and yahoo make bussines on the net.
    what profit gain a site when a user is redirected there and same user after less then 30 seconds go to other site?
    what useless costs you have because somebody redirect users to your site? Keep in mind that we talking about google or yahoo, and about this specific case.
    don't say that costs does not matter or are less because are a lot of indirect costs and in this case could be easy avoided.
    Again, the user would have been banned, so you wouldn't want to do business or communicate with them anyway.

    Quote Originally Posted by oesxyl View Post
    not banned, redirected to another site, is something else and is clear not the same thing
    Quote Originally Posted by Len Whistler View Post
    Another useful feature to add to a bad word filter is to block them from your site temporarily if they abuse your comment/forum page.

    Once they submit a "bad" word their IP is entered into a database - MySQL or TXT file - and at the same time they are directed to an alternate site - yahoo.com, google.com - using the php header function.
    I'm not going to debate this anymore. We're just going to disagree.
    Cheers

  • #12
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Inigoesdr View Post
    Again, the user would have been banned, so you wouldn't want to do business or communicate with them anyway.
    "banned" on this site => redirected to "alternate site - yahoo.com, google.com"
    I talk about google and yahoo here

    I'm not going to debate this anymore. We're just going to disagree.
    Cheers [/QUOTE]
    yes, I agreed, but I repeat:
    Len Whistler solution is good if you redirect to "-" to don't harm anybody. That's all.

    regards

  • #13
    New to the CF scene
    Join Date
    Aug 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    use a web service

    I have had a lot of luck with the WebPurify profanity filter , bad word filter, etc. It really is impossible to write something that is effective!

  • #14
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes! I am the NEWBIE! (sorry)

    include ("filter.php");
    $str = <<<EOF
    $comments
    EOF;
    // bad words:
    $replace_str = "@#$*!";
    $bad_words = array('****','****','****','sucks','suck');
    print ReplaceBadWords($str, $bad_words, $replace_str);

    Where you say $comments... is the form input (or IM box input)...

    Does all that above code go above the <header> tag?
    And if so, do you do something like this... $comments = $_GET['bio_body']; ///bio_body is the form text field i am using

    if not... how do you sandwich HTML code (((canned form text field))) into where the $comments variable is?

    Sorry if i am showing major ignorance here...

    Help appreciated

    Steve
    Last edited by s7mo; 01-03-2011 at 11:30 PM.

  • #15
    New to the CF scene
    Join Date
    Jan 2011
    Location
    Northampton, UK
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    re: Language filter.

    Okay guys,

    Looking through this example, is something which I would have created several years ago. I'm not here to brag, just simply here to give you my own engineered peice of code.

    I have a framework, which handles multiple languages etc, therefore i needed a table in my database to store swear words for different languages. Secondly, yes i did use a database to hold the words.

    Now, I thrive on performance engineering, so, to loop through each word and looking through my table with loads of threads = not fast enough. Looping through my table building an array of all values once each time, too slow...

    Also this example if you had "***" as your bad word, and i wanted to type "assistance" itll show up as "@#$*!istance", yeah this is NOT good. so let's use an expression match to ensure its whole words ONLY.

    NOT TESTED, SO POSSIBLE MINOR ERRORS, CACHING MAY THROW SOME PROBLEMS IF YOU NEED TO SET THE MODE TO 0777. BUT THERE SHOULDN'T BE ANYTHING MAJORLY WRONG. Enjoy!

    1. Here is your database table query...
    Code:
    CREATE TABLE IF NOT EXISTS `pfx_language_filter` (
      
      `lf_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
      `lf_phrase` VARCHAR(45) NOT NULL,
      `lf_replace` VARCHAR(45) NOT NULL DEFAULT '*****',
      `lf_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      
      PRIMARY KEY (`lf_id`),
      UNIQUE `NODUPWORD` (`lf_phrase`)
      
    ) ENGINE=InnoDB AUTO_INCREMENT=1;
    
    --
    
    INSERT INTO `pfx_language_filter` (`lf_phrase`) VALUES ('****'),('****'),('arse'),('***'),('dick');
    2. We need our php function... (func.languageFilterWords.php)
    PHP Code:
    <?php
    function languageFilterWords($str$ignore false) {
        if (!
    $ignore) {
          
    $cache = new QuickCache('/var/www/vhosts/usr/httpdocs/cache_dir/');
          
    $cache->expire 0;
          
          if (!
    $words $cache->fetch('langFilter')) {
            
    // you need to connect to your database here by the way...
            
    $wordsQ mysql_query('SELECT lf_phrase, lf_replace FROM pfx_language_filter ORDER BY LENGTH(lf_phrase) DESC, lf_phrase ASC');
            
            
    $words = array();
            while (list(
    $naughty,$good) = mysql_fecth_array($wordsQ))
               
    $words[$naughty] = $good;

            
    $cache->save('langFilter'$words);
          }
          
          
    // foreach words, look into our string for any instance of them,
          // ONLY when they are WHOLE words, not in the middle of words,
          // assistance = OK!, *** = ****!. yeah?
          
    foreach ($words as $badword => $goodword)
            if (
    preg_match($expr '~(^|[^a-z0-9]?)(' $badword '?)($|[^a-z0-9])~iU'$str))
              
    $str preg_replace($expr"\\1{$goodword}\\3"$str);
        }
        
        return 
    $str;
      }
    3. you will need my caching class which i will offer you all free, under the Open Source MIT License version 3.0, keep all credits please.
    PHP Code:
    <?php
    <?php

    /**
     * Project:     QuickCache
     * File:        class.quickcache.php
     *
     * THIS LIBRARY IS IN NO WAY, SHAPE OR FORM TO BE CONSIDERED
     * ANYTHING LIKE MEMCACHE, MEMCACHED ETC, IT IS NOT!!! HOWEVER
     * MEMCACHE IS ONLY USEFUL WHEN USED ON MASSIVE SYSTEMS, IE.
     * FACEBOOK, IF THE CACHE IS NOT UPDATED IT ACTUALLY SLOWS THE
     * PERFORMANCE DOWN! THIS LIBRARY IS DESIGNED TO HOLD CACHE FOR
     * SMALL PHP SOURCES TEMPORARILY OR PERMANENT DATA.
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * @link http://www.itsash.co.uk/
     * @copyright 2010 - 2011 Ashley Meadows. All rights reserved.
     * @author Ashley Meadows <takingsides [at] gmail [dot] com>
     * @package QuickCache
     * @version 1.0.0
     */

    final class QuickCache {

      
    // Variables / Constants
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

      
    public $delete_old false$overwrite true$expire 3600;
      private 
    $_path;

      
    // Class Constructor/Destructor
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

      
    public function __construct($path) {
        if (!
    is_dir($path))
          
    user_error('Cache directory does not exist.'E_USER_ERROR);
        if (!
    is_writable($path))
          
    user_error('Cannot write to cache directory.'E_USER_ERROR);
        if (!
    is_readable($path))
          
    user_error('Cannot read from cache directory.'E_USER_ERROR);
        
        
    $this->_path $path;
      }

      public function 
    __destruct() {
        if (
    $this->delete_old)
          
    $this->_delete_expired_cache();
      }
        
        
    // Public Methods
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
      
    public function save($key$data$expires null) {
        
    $fp = @fopen($this->_generate_cache_file($key$expires), 'w+');
        
    fwrite($fpserialize($data));
        
    fclose($fp);
      }
      
      public function 
    fetch($key) {
        if (
    $filename glob($this->_path $key '%*.cach')) {
          list(
    $cacheKey$cacheExpire) = explode('%'basename($filename[0]));
          if (
    $cacheExpire intval($cacheExpire))
            
    $this->_delete_cached_data($filename[0], $cacheExpire);

          return @
    unserialize(@file_get_contents($filename[0]));
        } else {
          return 
    false;
        }
      }
        
      public function 
    delete($keys) {
        foreach ((array) 
    $keys as $key)
          if (
    $filename glob($this->_path $key '%*.cach'))
            @
    unlink($filename[0]);
      }
        
        
    // Private Methods
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
      
    private function _generate_cache_file($hash$time null) {
        
    $cfiletime is_null($time) ? $this->expire $time;
        
    $cfilename sprintf('%s%%%d.cach'$this->_path $hash$cfiletime);

        foreach (
    glob($this->_path $hash '%*.cach') as $cachefile) {
          list(
    $hashKey$hashExpire) = explode('%'$cachefile);
          if ((!
    $this->overwrite) && ($hashKey == $hash))
            
    user_error('Overwritting is not allowed for key (' $hash ').'E_USER_ERROR);

          if (
    intval($hashExpire) != $cfiletime)
            @
    unlink($cachefile);
        }

        return 
    $cfilename;
      }
        
        
    // Protected Methods
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
      
    protected function _delete_cached_data($cache_file$cache_expires) {
        if (((
    filemtime($cache_file) + $cache_expires) <= time()))
          return 
    unlink($cache_file);

        return 
    false;
      }
        
      protected function 
    _delete_expired_cache() {
        foreach ((array) 
    glob($this->_path '*.cach') as $cachefile) {
          if (!
    file_exists($cachefile))
            continue;

          list(, 
    $expires) = explode('%'$cachefile);

          if (
    $expires intval($expires))
            if ((
    $expires filemtime($cachefile)) <= time())
              @
    unlink($cachefile);
        }
      }
    }

    4. Finally, you're ready to use it...
    PHP Code:
    <?php

    include_once ('class.quickcache.php');
    include_once (
    'func.languageFilterWords.php');

    $string "Hello! i need assistance because with my **** iphones battery sucks dick.";

    var_dump(languageFilterWords($string));

    //output: Hello! i need assistance because with my ***** iphones battery sucks ****.
    FINALLY!

    Remember to make sure you keep re-caching your data, every time you add/remove or edit any of these words in the database. that way it will keep things fast!

    PHP Code:
    <?php
    $cache 
    = new QuickCache('/var/www/vhosts/usr/httpdocs/cache_dir/');
    $cache->expire 0;
          
    // you need to connect to your database here by the way...
    $wQ mysql_query('SELECT lf_phrase, lf_replace FROM pfx_language_filter ORDER BY LENGTH(lf_phrase) DESC, lf_phrase ASC');
            
    $words = array();
    while (list(
    $naughty,$good) = mysql_fecth_array($wQ))
      
    $words[$naughty] = $good;

    $cache->save('langFilter'$words);

    mysql_free_result($wQ);
    Last edited by ItsAsh; 01-27-2011 at 12:21 PM. Reason: fixed a bug i have noticed.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •