我所做的是遍历tweet的对象,并且在每次迭代中我检查tweet是否包含存储在数组中的任何单词。
这个例子显示了preg_match,但是如果我使用strpos()或stripos(),我就会遇到同样的问题。
函数如下:
function contains($tweet, $words) {
$count = 0;
foreach($words as $word) {
if (preg_match('/'.$word.'/',$tweet)) {
$count++;
}
}
return $count;
}
问题是,除非我硬编码一个单词,否则它不会经过if语句。$word确实包含正确的值,并且肯定是字符串,因为我已经尝试在循环中echo和var_dump输出值。
用法:
$results = $twitter->request('search/tweets', 'GET', $parameters);
$negative_words = file("negative-words.txt");
foreach($results->statuses as $tweet) {
echo contains($tweet->text, $negative_words);
}
我试着四处寻找,尝试了许多不同的方法,但都没有奏效。有人知道问题是什么吗?
工作的例子:
<?php
function contains($tweet, $words)
{
$count = 0;
array_walk($words,function($word) use(&$count,$tweet){
if(strpos($tweet,$word)!==false){
$count++;
}
});
return $count;
}
列表返回的字符串末尾有一些狡猾的回车符。通过使用str_replace()删除它们,问题得到了解决。