Bad Word Filter, how do I replace words by their length?

后端 未结 2 1377
情歌与酒
情歌与酒 2021-01-29 06:18

I have this PHP Code, it generates random characters where there is a bad word:

$wordreplace = array (
  \"!\",
  \"#\",
  \"@\",
  \"&\",
  \"^\",
  \"$\",
         


        
2条回答
  •  既然无缘
    2021-01-29 06:55

    You might be overthinking this. The whole first part of your code is meant to find a randomized replacement for the bad word. Only those last two lines matter, and you can replace them with:

    $content = preg_replace_callback(
        $badwords,
        function ($matches) {
            return str_repeat('*', strlen($matches[0]));
        },
        $content
    );
    

    To make this work, though, you need to wrap your badwords in a 'capture group' like so:

    $capture_badwords = [];
    foreach ($word in $badwords) {
        $capture_badwords[] = "/(".$word.")/";
    }
    

    This should produce an array like this:

    ["/(abadword)/", "/(anotherbadword)/", "/(afourletterword)/", ... ]
    

    preg_replace_callback lets you define a function with which you can manipulate the matched group.

    Putting this together in an example:

    $badwords = [ "/(dog)/", "/(cat)/", "/(here)/" ];
    //"#\((\d+)\)#"
    $phrase = "It is just dogs chasing cats in here.";
    
    echo preg_replace_callback(
            $badwords,
            function ($matches) {
                return str_repeat('*', strlen($matches[0]));
            },
            $phrase
        );
    

    Yields:

    It is just ***s chasing ***s in ****.

提交回复
热议问题