Forum Moderators: coopster
I`m trying to implement a bad word filter for a guestbook. I`ve stored the words in a database, now I need to loop through them and filter out unwanted words.
I`ve created a function as follows:
function badWordFilter() {
global $comments;
$query = "SELECT * FROM mg_badwords";
$result = mysql_query($query);
$row = mysql_fetch_array($result);for ($n=0; $n<sizeof($row); $n++)
{
$comments = eregi_replace($row['mg_badword'][$n], $row['mg_newword'][$n], $comments);
}
return $comments;
}
Problem I have is only the first row is working. I assume its something to do with the for loop?
Thanks.
:)
function badWordFilter() {
global $comments;
$query = "SELECT * FROM mg_badwords";
$result = mysql_query($query);while ($row = mysql_fetch_array($result))
{
$bad[] = $row['mg_badword'];
$good[] = $row['mg_newword'];
}for ($n=0; $n<sizeof($bad); $n++)
{
$comments = eregi_replace($bad[$n], $good[$n], $comments);
}
return $comments;
}
Works like a charm.
:)
something i read yesterday whilst looking for ways to speed up code is to take the sizeof() out of the for loop, and define it beforehand. that means you are then only looping and comparing a constant instead of the script having to find the sizeof() every time you loop.
depending on how big your list of bad words is, it could help quite a bit
e.g.
$a = sizeof($row)
for ($n=0; $n < $a; $n++)
I do remember a story a C++ programmer told me about writing some code to test timings. The optimiser did the job so well it removed all the delays deliberately inserted.
With perl, even more optimisation happens... Perl is thought of as an interpreted scripting language, but the whole script is read in and converted to an internal virtual machine code (with lots of optimisation along the way) before being executed.
Having said that, I agree with lorax that it is a good idea to write code which is efficient no matter how good the compiler or interpreter's optimisation algorithms are. i.e. Just think of PHP as interpretted, pure and simple, and any further optimisation the zend engine gives you will be a bonus.
Shawn