View Single Post
Old 03-10-2010, 06:27 AM   #2 (permalink)
delayedinsanity
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

Usually I write all my comments as, well, comments, but I'll go over a few things and just plaster the code below for ya.

- First of all, not sure if the code you pasted is what you're actually testing, but when you echo $ToFilter at the bottom, you haven't ever actually run your function on it.

- Unless you have a specific need for fread, file_get_contents is quicker and does the same thing in one line instead of three. PHP is like a large city, there's 20 routes to get anywhere, and there's usually a few that are better than others.

- Don't use error suppression unless you have no other choice. Especially in your case, because the function will continue to run having no data to work with.

- str_replace is much faster than preg_replace. Use it when you can. Also, you're spending time looking for the words, and then looking for them again to perform the replace. That's like going to two bathrooms for one shave.

- Loops, again, should only be performed when there isn't a better method (though I understand being new you may not have learned them all yet, just letting you know!). PHP has an extensive list of string functions, and I'll show you one of them that negates the need for for()

- When all else fails debugging, don't be afraid to drink a few beers and work on your car. It's much more rewarding than this crap anyways... or maybe that's just because I've been working 14 hour days for the past week with pain in the ass clients...

- Oh yeah. I try not to change variables when helping somebody with code, but CamelCase drives me batty. Sorry.

php Code:
<?php

$input = 'quotes.txt';
$wordsfile = 'words.txt';

$string = file_get_contents( $input );

echo LangFilter( $string, $wordsfile );


function LangFilter( $string = '', $wf ) {

    if ( empty( $string ) || ! file_exists( $wf ) )
        return FALSE;

    $words = file( $wf );

    foreach ( $words as $search ) {
        $search = trim( $search );
        $replace = str_repeat( '*', strlen( $search ) ); // No loopy inside loopy
        $string = str_ireplace( $search, $replace, $string );
    }

    return $string;

}
delayedinsanity is offline  
Reply With Quote
The Following User Says Thank You to delayedinsanity For This Useful Post:
Tim Dobson (03-10-2010)