4

最初に単語のファイル全体を配列に処理してから、ファイル内の単語のいずれかに渡された文字列をチェックするこのコードがあります。一致する場合は、* に置き換えます。

ファイルは次のようなものです:

wordalex
wordjordan
wordjohn
....

残念ながら、私が渡した文は、私が期待する方法でフィルタリングされていません. 実際には何も起こりません。与えられたコードを見て、助けてください。

$comment = "the wordalex if this doesn't get caught!";
$filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES);
//print_r($filterWords);
$textToPrint = filterwords($comment,$filterWords );
echo $textToPrint;

function filterwords($text, $filterArray){
    $filterCount = sizeof($filterWords);
    for($i=0; $i<$filterCount; $i++){
        $text = preg_replace('/\b'.$filterWords[$i].'\b/ie',"str_repeat('*',strlen('$0'))",$text);
    }
    return $text;
}

そのため、実際には元の文に吟遊詩人の言葉がありますが、投稿の目的で削除されています。

ありがとうございました

4

2 に答える 2

2

関数定義では、単語 list を呼び出します$filterArray

function filterwords($text, $filterArray){

ただし、関数全体で、それを呼び出します$filterWords

$filterWords定義内で名前を に変更するか、各出現箇所の名前を に変更し$filterArrayます。

于 2012-07-28T06:13:36.457 に答える
1

$filterWords空の行を無視してビルドします。あなたは実際に両方が必要FILE_IGNORE_NEW_LINESですFILE_SKIP_EMPTY_LINES

$filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

置換アレイを構築します。

$replacements = array();
$patterns = array();

foreach ($filterWords as $word) {
    // ignore empty words, just in case
    if (empty($word)) continue;        

    $replacements[] = str_repeat('*', strlen($word));
    $patterns[] = "/\b$word\b/i";
}

そして、実行しますpreg_replace()

$textToPrint = preg_replace($patterns, $replacements, $comment);

これはHello ******** NOTwordjohnから得られHello wordJoHN NOTwordjohnます。

于 2012-07-28T05:53:36.803 に答える