从数组文件txt中检查字符串中的坏词

时间:2017-01-07 22:50:56

标签: php arrays

$badwords = array('Hello' => 1, 'aa' => 1, 'vv' => 1);  

$string = "Hello how are you";

$words = explode(' ', $string);
foreach($words as $word) {
        $word = preg_replace('/[^A-Za-z0-9]*/', '', $word);
        if (isset($badwords[$word])) {
            echo("Found $word<br>");
        }else{
            echo("ok $word<br>");
        }
}

我试图从txt文件中获取单词并将所有数据放入并检查但我不能... 你能帮助我吗?感谢。

问:我想从txt文件中检查字符串中的单词...

2 个答案:

答案 0 :(得分:0)

你这样使用修剪。

$badwords = array('Hello' => 1, 'aa' => 1, 'vv' => 1);  

    $string = "Hello, how are you";

    $words = explode(' ', $string);
        foreach($words as $word) {
        $word = trim($word, " ,.!?");
        if (isset($badwords[$word])) {
            echo("Found $word<br>");
        }else{
            echo("ok $word<br>");
    }
        }

测试代码:

<?php
$badwords = array('Hello' => 1, 'aa' => 1, 'vv' => 1);

$string = "Hello, how are you";

$words = explode(' ', $string);
foreach($words as $word) {
    $word = trim($word, " ,.!?");
    if (isset($badwords[$word])) {
        echo("Found $word<br>");
        echo "\n";
    }else{
        echo("ok $word<br>");
        echo "\n";
    }
}

输出:

ei@localhost:~$ php test.php
Found Hello<br>
ok how<br>
ok are<br>
ok you<br>

编辑:

<?php
$badwords = file("aaa.txt", FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$badwords = array_flip($badwords);

$string = "Hello how are you";

$words = explode(' ', $string);
    foreach($words as $word) {
    if (isset($badwords[$word])) {
        echo("Found $word<br>");
        echo "\n";
    }else{
        echo("ok $word<br>");
        echo "\n";
    }
}

aaa.txt:

Hello
aa
vv

输出:

ei@localhost:~$ php test.php
Found Hello<br>
ok how<br>
ok are<br>
ok you<br>

答案 1 :(得分:0)

  

我试图从txt文件中获取单词并将所有内容放入数组并检查但是   我不能......你能帮助我吗?

要将txt文件读取到array使用file()

$lines = file('/path/to/file.txt');
// $lines is an array and contains all lines of the txt file, loop it:
foreach($lines as $line)
{
  $words = explode(' ', $line);
  foreach($words as $word)
  {
     // implement your logic here
  }
}