strpos() == false 计算不正确

问题描述 投票:0回答:2

我试图排除那些文本中没有

RT @
的推文。 这是我的代码:

foreach ($tweets3 as $item)
{
    $text = $item->text;
    $check = 'RT @';
    $result = strpos($text, $check);
    if ($result == false)
        continue;
}

但是这些推文也被排除在外

Mention text : RT @IBMcloud: A few #cloud highlights from the @IBM Annual Report.

RT @holgermu: MyPOV - Nice way to put out our annual report in an interactive (engaging?) format - here is @IBM's 

RT @TopixPolitix: Chinese State and Citizens Must Battle Airpocalypse Together

尽管他们的文字中有

RT @
。为什么?

php strpos
2个回答
1
投票

请参阅 文档中的此警告:

strpos()

此函数可能返回布尔值 FALSE,但也可能返回计算结果为 FALSE 的非布尔值。使用 === 运算符来测试该函数的返回值。

正如文档所述,

strpos()
可以返回计算结果为布尔值
FALSE
的值。例如,如果字符串开头有匹配项,
strpos()
将返回
0

为了避免歧义,请始终使用严格比较 (

===
) 而不是松散比较 (
==
)(只要可能):

foreach ($tweets3 as $item)
{
    $text = $item->text;
    $check = 'RT @';
    $result = strpos($text, $check);

    // if "RT @" text not found in tweet, skip to next iteration
    if ($result === false) continue;
}

0
投票

我认为你的逻辑已经颠倒了。如果找到文本,

$result
将保存数值。您希望您的支票是:

        if($result !== false)
                continue;
© www.soinside.com 2019 - 2024. All rights reserved.