gpt4 book ai didi

php - 从回调内更新 preg_replace_callback 外部的变量

转载 作者:行者123 更新时间:2023-12-02 04:21:49 25 4
gpt4 key购买 nike

我有一个看起来像这样的函数...

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。

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

谢谢

最佳答案

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

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 手册。

关于php - 从回调内更新 preg_replace_callback 外部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com