麻烦简单的PHP亵渎过滤器 [英] Trouble with simple PHP profanity filter

查看:170
本文介绍了麻烦简单的PHP亵渎过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的亵渎过滤器在PHP中。任何人都可以告诉我为什么,在下面的代码中,过滤器的工作原理(它将打印[显式])的$元素数组,而不是我从文本文件中构建的$行数组?
$函数clean($ str){

$ handle = fopen(badwords.txt,r); b $ b pre $
if($ handle){
while(!feof($ handle)){
$ array [] = fgets($ handle,4096);
}
fclose($ handle);


$ vowels = array(a,e,i,o,u,A,E,I, O,U);

$ filter =[explicit];
$ clean = str_replace($ array,$ filter,$ str);
返回$ clean;





当使用$元音代替$ array时,除了小写元音返回:

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $

而不是

[显式]

不确定为什么这样做了。要么

任何想法?

谢谢!

解决方案

我修改了Davethegr8的解决方案,以获得以下工作示例:

 函数clean($ str){

global $ clean_words;

$ replacement ='[explicit]';
$ b $ if(empty($ clean_words)){
$ badwords = explode(\\\
,file_get_contents('badwords.txt'));

$ clean_words = array();
$ b foreach($ badwords as $ word){
$ clean_words [] ='/(\ b'。trim($ word)。'\b)/ si';


$ b $ out = preg_replace($ clean_words,$ replacement,$ str);
返回$ out;
}


I am writing a simple profanity filter in PHP. Can anyone tell my why, in the following code, the filter works (it will print [explicit]) for the $vowels array and not the $lines array which I constructing from a text file?

 function clean($str){

$handle = fopen("badwords.txt", "r");
if ($handle) {
   while (!feof($handle)) {
       $array[] = fgets($handle, 4096);
   }
   fclose($handle);
}

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");

$filter = "[explicit]";
$clean = str_replace($array, $filter, $str);
return $clean;
 }

When using $vowels in replace of $array, it works except for lowercase vowels which return:

 [[expl[explicit]c[explicit]t]xpl[explicit]c[explicit]t]

 instead of 

 [explicit]

Not sure why that is going on, either.

Any ideas?

Thanks!

解决方案

I modified Davethegr8's solution to get the following working example:

 function clean($str){

global $clean_words; 

$replacement = '[explicit]';

if(empty($clean_words)){
    $badwords = explode("\n", file_get_contents('badwords.txt'));

    $clean_words = array();

    foreach($badwords as $word) {
        $clean_words[]= '/(\b' . trim($word) . '\b)/si';
    }
}

$out = preg_replace($clean_words, $replacement, $str);
return $out;
 }

这篇关于麻烦简单的PHP亵渎过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆