Laravel bad wordfilter as a helper

I'm trying to make my own bad word filter, and it works great except when I have multiple words in a sentence. So now what it does is it takes the values ​​from the database and then loops it and has to replace the words of the declaration.

Let me say that I (in Dutch) is a sentence Deze kanker zooi moet eens stoppen! Het is godverdomme altijd het zelfde zooitje.

. These are the words that need to be replaced in the database:

kanker

and godverdomme

.

So, I have in my database:

values

All is well, except that 2 hordes have to be replaced, then he doesn't want to replace ...

My helper function:

public static function Filter($value)
    {
        $badwords = DB::table('badwords')->get();

        foreach ($badwords as $badword)
        {
            $replaced = str_ireplace($badword->bad_word, $badword->replacement, $value);
        }

    return $replaced;
    }

      

Hope someone can help me :)

Regards,

Robin

+3


source to share


1 answer


For each iteration in your foreach loop, you set the value $replaced

to what it returns str_ireplace

.
At the end of the function, you will return a value in which only the last bad word should be replaced.

str_ireplace

takes either a single string value or an array of string values ​​to replace as the first and second parameters, which means that you could instead create two arrays that you fill in in a loop foreach

and then run str_ireplace

after the loop, something like:



$words = []; 
$replace = [];
foreach ($badwords as $badword) {
    array_push($words, $badword->bad_word);
    array_push($replace, $badword->replacement);
}
return str_ireplace($words, $replace, $value);

      

+2


source







All Articles