从回调内更新preg_replace_callback之外的变量

时间:2015-04-27 09:47:19

标签: php preg-replace-callback

我有一个看起来像这样的功能......

function filterwords($input='poo poo hello world bum trump'){

    $report_swear = 0;

    $badwords = array('poo','bum','trump');

    $filterCount = sizeof($badwords);

    for($i=0; $i<$filterCount; $i++){
            $input = preg_replace_callback('/\b'.preg_quote($badwords[$i]).'\b/i', function($matches) use ($report_swear) {
                $report_swear++;
                return str_repeat('*', 4);
            }, $input);
    }

    print_r($report_swear);

    return $input;

}

在这个例子中,我希望$ report_swear变量返回4,但它仍然返回0.

我知道如何在回调中改变这一点吗?

由于

1 个答案:

答案 0 :(得分:5)

我不确定你到底想做什么,但请注意你可以使用preg_replace_*的第4个参数作为计数器。您可以构建一个模式作为替换,而不是循环所有单词(优点是您的字符串只被解析一次,而不是每个单词一次)

function filterwords($input='poo poo hello world bum trump'){
    $badwords = array('poo','bum','trump');
    $badwords = array_map('preg_quote', $badwords);
    $pattern = '/\b(?:' . implode('|', $badwords) . ')\b/i';

    $result = preg_replace($pattern, '****', $input, -1, $count);
    echo $count;
    return $result;
}

如果你想考虑单词长度:

function filterwords($input='poo poo hello world bum trump'){
    $badwords = array('poo','bum','trump');
    $badwords = array_map('preg_quote', $badwords);
    $pattern = '/\b(?:' . implode('|', $badwords) . ')\b/i';

    $result = preg_replace_callback($pattern, function ($m) {
        return str_repeat('*', strlen($m[0]));
    }, $input, -1, $count);
    echo $count;
    return $result;
}

注意:如果输入字符串或坏词列表包含unicode字符,则需要将u修饰符添加到模式中,并使用mb_strlen代替strlen。有关详细信息,请参阅php手册。

相关问题