我有一个包含几条Twitter推文的数组,并希望删除此数组中包含以下单词之一的所有推文blacklist | blackwords | somemore
谁可以帮我解决这个案子?答案 0 :(得分:6)
这是一个建议:
<?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] );
}
}
}
?>
答案 1 :(得分:4)
您可以使用array_filter()功能:
$badwords = ... // initialize badwords array here
function filter($text)
{
global $badwords;
foreach ($badwords as $word) {
return strpos($text, $word) === false;
}
}
$result = array_filter($tweetsArray, "filter");
答案 2 :(得分:4)
检查此样本
$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'));
答案 3 :(得分:2)
你可以通过很多方式实现,所以如果没有更多信息,我可以提供这个真正的起始代码:
$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);
答案 4 :(得分:1)
使用正则表达式:
preg_grep($array,"/blacklist|blackwords|somemore/",PREG_GREP_INVERT)
但是我警告你,这可能是有效的,你必须在黑名单中处理标点字符。