开发者

php -> delete items from array which contain words from a blacklist

I have got an array with several twitter tweets and want to delete all tweets in this array which c开发者_开发知识库ontain one of the following words blacklist|blackwords|somemore

who could help me with this case?


Here's a suggestion:

<?php
$banned_words = 'blacklist|blackwords|somemore';
$tweets = array( 'A normal tweet', 'This tweet uses blackwords' );
$blacklist = explode( '|', $banned_words );

//  Check each tweet
foreach ( $tweets as $key => $text )
{
    //  Search the tweet for each banned word
    foreach ( $blacklist as $badword )
    {
        if ( stristr( $text, $badword ) )
        {
            //  Remove the offending tweet from the array
            unset( $tweets[$key] );
        }
    }
}
?>


You can use array_filter() function:

$badwords = ... // initialize badwords array here
function filter($text)
{
    global $badwords;
    foreach ($badwords as $word) {
        return strpos($text, $word) === false;
    }
}

$result = array_filter($tweetsArray, "filter");


use array_filter

Check this sample

$tweets = array();

function safe($tweet) {
    $badwords = array('foo', 'bar');

    foreach ($badwords as $word) {
        if (strpos($tweet, $word) !== false) {
            // Baaaad
            return false;
        }
    }
    // OK
    return true;
}

$safe_tweets = array_filter($tweets, 'safe'));


You can do it in a lot of ways, so without more information, I can give this really starting code:

$a = Array("  fafsblacklist hello hello", "white goodbye", "howdy?!!");
$clean = Array();
$blacklist = '/(blacklist|blackwords|somemore)/';

foreach($a as $i) {
  if(!preg_match($blacklist, $i)) {
    $clean[] = $i;
  }
}

var_dump($clean);


Using regular expressions:

preg_grep($array,"/blacklist|blackwords|somemore/",PREG_GREP_INVERT)

But i warn you that this may be inneficient and you must take care of punctuation characters in the blacklist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜