duai4379 2017-11-07 09:33
浏览 37
已采纳

用星星和输出数组替换php坏词

Following php function is being used to replace bad words with starts but I need one additional parameters that will describe either bad words found or not .

    $badwords = array('dog', 'dala', 'bad3', 'ass');
    $text = 'This is a dog. . Grass. is good but ass is bad.';
    print_r( filterBadwords($text,$badwords));


    function filterBadwords($text, array $badwords, $replaceChar = '*') {
$repu = preg_replace_callback(array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords),
        function($match) use ($replaceChar) {
                    return str_repeat($replaceChar, strlen($match[0])); },
                    $text

                    );
 return array('error' =>'Match/No Match', 'text' => $repu );   
}// Func

Output if badwords found should be like

Array ( [error] => Match[text] => Bad word dog match. )

If no badwords found then

Array ( [error] => No Match[text] => Bad word match. )

  • 写回答

2条回答 默认 最新

  • doutang9037 2017-11-07 09:49
    关注

    You can use the following:

    function filterBadwords($text, array $badwords, $replaceChar = '*') {
       //new bool var to see if there was any match
        $matched = false;
        $repu = preg_replace_callback(array_map(
            function($w)
            {
                return '/\b' . preg_quote($w, '/') . '\b/i'; 
            }, $badwords),
            //pass the $matched by reference
            function($match) use ($replaceChar, &$matched)
            {
                //if the $match array is not empty update $matched to true
                if(!empty($match))
                {
                    $matched = true;
                }
                return str_repeat($replaceChar, strlen($match[0]));
            }, $text);
        //return response based on the bool value of $matched
        if($matched)
        {
            $return = array('error' =>'Match', 'text' => $repu );
        }
        else
        {
            $return = array('error' =>'No Match', 'text' => $repu );
        }
        return $return;   
    }
    

    This uses reference and if condition to see if there were any matches and then returns response based on that.

    Output(if matched):

    array (size=2)
      'error' => string 'Match' (length=5)
      'text' => string 'This is a ***. . Grass. is good but *** is bad.'
    

    Output(if none matched):

    array (size=2)
      'error' => string 'No Match' (length=8)
      'text' => string 'This is a . . Grass. is good but  is bad.'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题