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条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题