Ignore whitespace str_replace PHP

Good evening.
I have in php an array of banned words.
With this code I replace the banned words with * in a string:

foreach ($wordlist as $word)
if (stripos($str, $word) !== false)
$str = str_ireplace($word, str_repeat(‘*’, strlen($word)), $str);
return $str;

The problem is that some users add spaces within words, so the code does not find them.

Example:
Banned word: apple
If I write apple is replaced with *****
If I write ap ple isn’t replaced

Is there a way to use str_ireplace ignoring white space?

Thanks so much

You could use another str_replace on the string to strip out the spaces before checking.

$stringToCheck = str_replace(' ', '', $str);

Also bear in mind str_replace can take arrays as parameters, so you may not need the foreach loop.
And for more complex replacements there is preg_replace

Thanks for the reply.
However it is not what I was looking
I need this for a chat, the spaces that there are at the beginning there must be also at the end

So you need to ignore some whitespace, but not other whitespace. That’s where it gets difficult, to distingush one piece of whitespace from another.
I imagine this would require preg_replace rather than the standard str_replace.

Have you considered using something like this or this.

1 Like

There’s a limit to how many of these you can trap, though - when your users realise that you’re stripping out spaces to catch them using banned words, they’ll find another way to get around it. One forum I use has a banned list, and you see that people will reverse some letters - everyone still knows what they mean, but it escapes the banned list. The other issue is making sure that what you do is not providing “false positives” and rejecting obscure combinations - there’s a town in northern England that some forums censor as its name contains an incredibly rude word.

1 Like

I did not think about it…
okay, so I will leave :slight_smile:

When you do think about it, the complexities of it are huge, way beyond a simple replace function.

Supposing you ban the word “fish” and someone types “fishface”, there is no space at the end.
The combinations are endless, along with $u8st!tut3d characters, then false positives.
So it may be best to go with @oddz suggestions for anything half way effective.

:smiley: I’m actually not very far from that place. It’s famous for something.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.