PHP Function: Word Filter
So, last night I was mainly experimenting with Whird, more specifically I was trying to build an internal search feature. This is something I’ve been putting off for long enough, and I’d really like to get it coded up. I didn’t finish it last night, but at least I’ve made a start.
Anyhow, during my experimentation I wrote this little PHP function for filtering words out of a string. Basically the function takes 2 strings as arguments before filtering words out of the first string based on words found in the second. I’ve posted it below for future reference:
function word_filter($string1,$string2){
$string1 = trim($string1);
$string1 = preg_replace('/s+/', ' ', $string1);
$string1 = explode(" ",$string1);
$wordcount = count($string1);
$i = 0;
while ($i < $wordcount) {
$string = $string1[$i];
if (strstr(strtolower($string2),strtolower($string))) {
$string1[$i] = "";
}
$i++;
}
$string1 = implode(" ",$string1);
return($string1);
}
Example usage
This is probably not the best example, but this:
$poem = <<<EOD
<p><em>GIVE me women, wine, and snuff <br />
Untill I cry out "hold, enough!" <br />
You may do so sans objection <br />
Till the day of resurrection: <br />
For, bless my beard, they aye shall be <br />
My beloved Trinity.</em></p>
EOD;
$common_words = 'and be but do for is it may me my not of the they there so was you';
echo word_filter($poem,$common_words);
Would output something like this:
GIVE women, wine, snuff
Untill cry out “hold, enough!”
sans objection
Till day resurrection:
For, bless beard, aye shall
beloved Trinity.
John Keats would be proud, not! Please feel free to optimise, or let me know if a one line equivalent already exists :)
Philip Newborough. Some Rights Reserved.
Licensed under a Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.









This site is intended for users, looking for solutions, fixes, tweaks to get things working just they way they should. User experiences are all here along with other helpful information for the new and experienced Linux (Ubuntu) user.
Recent Comments