ScoobyDooPHP;10916399 wrote:I'm trying to create a word filter for my website and here's my problem. if I user str_replace() then PHP only blocks the word if it has the same case, but if I use str_ireplace()
they work the same - str_replace would do the same to a part of a longer word (provided the capitalisation of the matched part matched)
ScoobyDooPHP;10916399 wrote: then it will block beep from beeper
and what if the word isn't 'beep' but a famous word that starts with 'f'? Don't you want to block it regardless of variations?
ScoobyDooPHP;10916399 wrote: for instance if someone adds the following text it will block it. (class, hello, etc ...)
I didn't follow that last bit above...
ScoobyDooPHP;10916399 wrote:
My code is like this.
$bad_words = array('nope', 'can\'t', 'write', 'these');
foreach( $bad_words AS $block ) :
$content = str_replace($block, '', $_POST['content']);
endforeach;
Thanks, Baylor
so you're effectively removing the bad words all together.
Anyhows, vectorialpx's solution will almost work for space seperated words, however once all 3 replacements are run, it will only stop the replacement of embedded wotds. so dabeepa won't be replaced, however beeper and dabeep still will have their beep components removed.
I'd reccomend using preg_replace as your core function, and match something like:
[non-alpha][bad-word][non-alpha] with '*'
ie, something like this (haven't tested it):
// bad words is set up
$bad_word_patterns = array();
foreach ( $bad_words as $word )
{
$bad_word_patterns[] = "/[^a-z].".preg_quote( $word )."[^a-z]./i";
}
$content = preg_replace( $bad_word_patterns, '****', $content );