I'd like to make a word filter, where should I start?
Moderator: General Moderators
I'd like to make a word filter, where should I start?
I have some input forms that store data in my SQL database, I just want to filter those forms for certain cuss words and phrases that i'd rather not show up on my site. Can someone point me in the right direction?
Thanks much :]
Thanks much :]
just build an array
Code: Select all
<?php
$bad = array(" word1 ", " word2 "); # etc etc
foreach ($bad as $word) {
$message = str_replace($word, "{edited}", strtolower($message));
}
?>this is better
The code I gave you earlier doesn't replace multiple occurrences of the same word within a variable so....
So with the other example if word1 was present more than once it would not be replaced the second and ensuing times.
Code: Select all
<?php
$bad = array("word1", "word2"); # etc etc
foreach ($bad as $word) {
$message = preg_replace("/$word/i", '{edited}', $message);
}
?>- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
like so:
outputs Hello, bob. How are you?
Code: Select all
$word = "bob";
$phrase = "Hello, bob. How are you?";
$phrase = str_replace('bob', '<strong>bob</strong>', $phrase);
echo $phrase;The docs for str_replace() show that both the search & replacement arguments can be arrays - so there's no need to do a foreach loop:
You can make the 2nd argument an array as well & replace particular words with particular replacements, rather than a blanket replacement for all bad words.
Code: Select all
<?PHP
$bad = array('bad1',
'bad2',
'bad3');
$input = 'I am a bad1ing mother bad3';
$clean_input = str_replace($bad,'{edited}',$input);
//$clean_input now = I am a {edited}ing mother {edited}
?>Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact: