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

Update variable outside of preg_replace_callback from within the 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 变量为 return 4,但它仍然是 returns 0.

知道如何在回调中更改它吗?

谢谢

我不确定您到底想做什么,但请注意,您可以使用 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 手册。