Search code examples
phparraysformsfwrite

php run write function only if input words don't match unwanted words from a text file


1) How to run php function to write input text to a file(text.txt) only if, not a single input word match from another text file(unwanted-words.txt)

<?php
$para = $_POST['para'];

if ($_POST)
    {
    $handle = fopen("text.txt", "a");
    fwrite($handle, $para . ":<br/>" );
    fclose($handle);
    }

?>

<form method="post">
Para:<input type="text" name="para"><br/>
<input type="submit" name="submit" value="Post">
</form>

2) Also, Which format should i use for unwanted words in file unwanted-words.txt :

badword,bad word,bad-word,bad_word,bad.word

OR

badword
bad word
bad-word
bad_word
bad.word

OR some other format

Thanks in advance


Solution

  • You can try this :

    Class Text in Text.php

    <?php
    
    /**
     * Text Class
     */
    
    class Text
    {
        //text string
        private $text;
    
        public function __construct($text)
        {
            //set value for $this->text for each objects/instances
            $this->text = $text;
        }
    
        //filter with a "filter file"
        public function filterFile($filter)
        {
            //get unwanted words file content :D
            $filter = file_get_contents($filter);
            //explode string every end of line for getting an array
            $filter = explode(PHP_EOL, $filter);
            foreach ($filter as $v) {
                if(preg_match("/$v/i", $this->text)){
                    $this->text = "";
                }
            }
            //return object for succesive methods (ex: $ex->a()->b()->c() )
            return $this;
        }
    
        //save modified string in file
        //first param => file name
        public function save($filename)
        {
            //set handle
            $handle = fopen($filename, 'a');
            //if true
            if($handle)
            {
                //write file
                fwrite($handle, $this->text.PHP_EOL);
            } else {
                return false;
            }
            //close handle
            fclose($handle);
        }
    }
    

    Unwanted words in txt file : unwanted-words.txt for example

    badword
    bad word
    bad-word
    bad_word
    bad.word
    

    I your page...

    <?php
    
    require "Text.php";
    if($_POST["para"])
    {
        //new instance of Text Class
        $text = new Text($_POST["para"]);
        $text->filterFile('unwanted-words.txt')->save("test.txt");
    }
    
    ?>
    
    <form method="post">
    Para:<input type="text" name="para"><br/>
    <input type="submit" name="submit" value="Post">
    </form>
    

    When submitting, text is append to file only if unanted word are not matched