word filter in PHP

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

word filter in PHP

Post by caracarn001 on Mon Apr 23, 2012 4:18 pm
([msg=65935]see word filter in PHP[/msg])

I'm trying to write a simple wordfilter in PHP. I read the words from a textfile (function getBlacklist)and put them in an array. Then I try to find out if a text contains any of the words in the array. If the text contains any of the 'bad words', the function should return true, otherwise it should return false. For some reason, it always returns false and I can't figure out why. Do you mind taking a look at my code? Maybe you see something I'm missing. :oops:

Code: Select all
function getBlacklist(){
   $result = array();
   $handle = fopen("blacklist.txt", "r");
   if ($handle) {
      while (($buffer = fgets($handle, 4096)) !== false) {
         $result[] =$buffer;
      if (!feof($handle)) {
         echo "Error: unexpected fgets() fail\n";

   return $result;

function contains_bad_words($text){
   foreach (getBlacklist() as $banned_word){
      $pos = strpos($text, $banned_word);
      if ($pos !== false) {
         echo "The string '$banned_word' was found in the string '$text'";
         echo " and exists at position $pos <br />";
         $result = true;
   return $result;
$text="this is an example 4u.";
   echo "String contains bad words";
   echo "String is fine";

-- Tue Apr 24, 2012 11:19 pm --

ok, figured it out.
It appears there's a space behind every word in the array i create. A simple trim solved it
User avatar
New User
New User
Posts: 42
Joined: Thu Nov 04, 2010 5:23 am
Blog: View Blog (0)

Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests