Page 1 of 1
I'd like to make a word filter, where should I start?
Posted: Wed Nov 14, 2007 7:10 am
by Darkzero
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 :]
just build an array
Posted: Wed Nov 14, 2007 9:46 am
by rturner
Code: Select all
<?php
$bad = array(" word1 ", " word2 "); # etc etc
foreach ($bad as $word) {
$message = str_replace($word, "{edited}", strtolower($message));
}
?>
Posted: Wed Nov 14, 2007 1:54 pm
by Darkzero
okay thanks, ill give it a try. :]
this is better
Posted: Wed Nov 14, 2007 6:18 pm
by rturner
The code I gave you earlier doesn't replace multiple occurrences of the same word within a variable so....
Code: Select all
<?php
$bad = array("word1", "word2"); # etc etc
foreach ($bad as $word) {
$message = preg_replace("/$word/i", '{edited}', $message);
}
?>
So with the other example if word1 was present more than once it would not be replaced the second and ensuing times.
Posted: Wed Nov 14, 2007 7:09 pm
by Jonah Bron
Are you sure, rturner? I have a php that emboldens every occurance of a given word, and it uses str_replace.

Posted: Thu Nov 15, 2007 10:12 am
by Jonah Bron
like so:
Code: Select all
$word = "bob";
$phrase = "Hello, bob. How are you?";
$phrase = str_replace('bob', '<strong>bob</strong>', $phrase);
echo $phrase;
outputs Hello,
bob. How are you?
Posted: Thu Nov 15, 2007 10:22 am
by pickle
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:
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}
?>
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.
Posted: Thu Nov 15, 2007 10:52 am
by Jonah Bron
Personally, if someone were to put an explanative in my website, I would eliminate it totally.

Posted: Thu Nov 15, 2007 5:24 pm
by rturner
pickle's right . no need for the loop
if you choose str_replace method maybe str_ireplace would be better for case-insensitive results.
Posted: Thu Nov 15, 2007 8:04 pm
by Jonah Bron
Eureka! Thanks, rturner! str_ireplace is just what I need for something I am working on.

Posted: Thu Nov 15, 2007 9:41 pm
by John Cartwright
I would probably stick to the preg_replace() alternative in this case, since it is backward compatible with php4.