How to code an efficient blacklist filter function in php?

Posted by achairapart on Stack Overflow See other posts from Stack Overflow or by achairapart
Published on 2010-06-02T13:56:15Z Indexed on 2010/06/02 15:53 UTC
Read the original article Hit count: 205

Filed under:
|
|

So, I have three arrays like this:

 [items] => Array
            ( [0] => Array
                  ( 
                    [id] => someid
                    [title] => sometitle
                    [author] => someauthor
                    ...
                  )
              ...
             )

and also a string with comma separated words to blacklist:

  $blacklist = "some,words,to,blacklist";

Now I need to match these words with (as they can be one of) id, title, author and show results accordingly.

I was thinking of a function like this:

  $pattern = '('.strtr($blacklist, ",", "|").')'; // should return (some|words|etc)

  foreach ($items as $item) {
          if ( !preg_match($pattern,$item['id']) || !preg_match($pattern,$item['title']) || !preg_match($pattern,$item['author']) ) 
               { 
                   // show item
               }
  }

and I wonder if this is the most efficient way to filter the arrays or I should use something with strpos() or filter_var with FILTER_VALIDATE_REGEXP ...

Note that this function is repeated per 3 arrays. However, each array will not contain more than 50 items.

© Stack Overflow or respective owner

Related posts about php

Related posts about regex