I have this PHP Code, it generates random characters where there is a bad word:
$wordreplace = array (
\"!\",
\"#\",
\"@\",
\"&\",
\"^\",
\"$\",
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 ****.