문제
PHP에서 간단한 욕설 필터를 쓰고 있습니다. 누구든지 다음 코드에서 필터가 텍스트 파일에서 제작하는 $ 행 배열이 아닌 $ Vowels 배열에 대해 필터가 작동하는 이유를 말할 수 있습니까?
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]
그것이 왜 일어나고 있는지 잘 모르겠습니다.
어떤 아이디어?
감사!
해결책 2
다음과 같은 작업 예를 얻기 위해 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;
}
다른 팁
필터의 출력에는 소문자 모음이 포함되어 있기 때문에 필터링하는 문자이기도합니다. 즉, 피드백 루프를 만들고 있습니다.
우선, 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);
제휴하지 않습니다 StackOverflow