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 开发者_如何学JAVAfilter_var with FILTER_VALIDATE_REGEXP ...
Note that this function is repeated per 3 arrays. However, each array will not contain more than 50 items.
Yours isn't bad. I'd typically use strpos
for something like this...
$items = filter($foo['items'], array('some','words','to','blacklist'));
function filter($items, $blacklist) {
$filtered = array();
foreach($items as $item) {
foreach($item as $key => $value) {
$pass = true;
foreach($blacklist as $filter) {
$pass = strpos($value, $filter) === false;
if(!$pass) break;
}
if($pass) $filtered[] = clone($item);
}
}
return $filtered;
}
To add a bit more sophistication, you can tokenize the strings you're checking by whitespace. The code would then become:
function filter($items, $blacklist) {
$filtered = array();
foreach($items as $item) {
foreach($item as $key => $value) {
$pass = true;
foreach(explode(' ', $value) as $word) {
$pass = !in_array($word, $blacklist);
if(!$pass) break;
}
if($pass) $filtered[] = clone($item);
}
}
return $filtered;
}
精彩评论