2009-08-01 65 views
1

我正在用PHP写一个简单的亵渎过滤器。任何人都可以告诉我为什么,在下面的代码中,过滤器工作(它会打印[显式])$ vowels数组,而不是我从文本文件构建的$ lines数组?简单的PHP亵渎过滤器的问题

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

当使用$元音替换$阵,它的作品,除了其返回小写元音:

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

instead of 

[explicit] 

不知道为什么这是怎么回事,无论是。

任何想法?

谢谢!

回答

1

我修改Davethegr8的解决方案,得到以下工作例如:

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; 
} 
1

因为过滤器的输出包含小写元音,它们也是您要过滤的字符。即你正在创建一个反馈循环。

+0

好点!谢谢 – littleK 2009-08-01 07:05:47

1

首先,file_get_contents是一个简单得多的函数来将文件读入变量。

$badwords = explode("\n", file_get_contents('badwords.txt'); 

其次,preg_replace提供了更灵活的字符串替换选项。 - http://us3.php.net/preg_replace

foreach($badwords as $word) { 
    $patterns[] = '/'.$word.'/'; 
} 

$replacement = '[explicit]'; 

$output = preg_replace($patterns, $replacement, $input); 
+1

这是一个很糟糕的代码示例您提供的只是badwords.txt中的最后一个单词将被替换为文本'[explicit]'。如果有的话,你应该简单地删除foreach并执行以下操作:$ output = preg_replace($ badwords,$ replacement,$ input); – Andy 2009-08-01 06:47:21

+1

@andy - 哈哈,哎呀。昨晚深夜,我忘了[]。 :) – davethegr8 2009-08-01 15:45:01