php 运行 仅当输入词与文本文件中不需要的词不匹配时才编写函数

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

1) 如何 运行 php 函数将输入文本写入文件 (text.txt) 仅当没有来自另一个文本文件的单个输入词匹配时 (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) 另外,对于文件 unwanted-words.txt 中不需要的词,我应该使用哪种格式:

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

badword
bad word
bad-word
bad_word
bad.word

或其他格式

提前致谢

你可以试试

$para = $_POST['para'];

// one badword per line in unwanted-words.txt                                      
$badwords = implode("|", file('unwanted-words.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));       

if (!preg_match("/(".$badwords.")/", $para, $matches)) {                                      
    file_put_contents('file.txt', $para.":<br/>", FILE_APPEND);                                                                                        
}  

你可以试试这个:

Class 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);
    }
}

txt 文件中不需要的词:例如不需要的-words.txt

badword
bad word
bad-word
bad_word
bad.word

我在你的页面...

<?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>

提交时,仅当未匹配的单词不匹配时,文本才会追加到文件中