【问题标题】:Strpos not working correctlyStrpos 无法正常工作
【发布时间】:2016-01-13 03:25:10
【问题描述】:

目前我在过滤它时遇到了一堆问题,因此只有包含字符串 http://www.example.com/?dl_name= 的帖子才能通过。

第一个 if 声明完美无缺,但第二个返回我正在抓取的每个帖子,即使是上面没有包含 URL 的帖子我做错了什么?

$url = ''.$element->href;
$html2 = file_get_html($url);
$title = $html2->find('.single-style1-title h1',0);
$s = $title->plaintext;
$str2 = explode ("MUSIC:", $s);
print '<br>';
$date = $html2->find('strong > a',0);
$n = $date->href;
$str = explode ("http://www.example.com/?dl_name=", $n);
if (strpos($title->plaintext,"VIDEO:")===FALSE) { 
    if (strpos($n,'http://www.example.com/?dl_name=') !== true) {   
        $image = $html2->find('.thumb-wrap img',0);
        //$date = $html2->find('strong > a',0);
        //$n = $date->href;
        print '<br><br>';
        echo $url;
        print '<br>';
        print htmlspecialchars_decode($image->src);
        print '<br>';
        print $str2[1];
        print '<br>';
        print $str[1];
    }
}   

【问题讨论】:

  • 我对 strpos 的使用无法正常工作 - 在那里,为您解决了这个问题 :-)

标签: php strpos


【解决方案1】:

问题出在这里:

if (strpos($n,'http://www.example.com/?dl_name=') !== true)

strpos 永远不会返回 true。引用from the docs

返回针存在的位置相对于 haystack 字符串的开始位置(与偏移量无关)。另请注意,字符串位置从 0 开始,而不是 1。

如果没有找到针,则返回 FALSE。

【讨论】:

  • 在不使用 strpos 的情况下,我该怎么做才能获得我正在寻找的输出?
  • @JohnDoe 如果您需要确保字符串中有 no 匹配项,那么只需反转您的条件:if (strpos(...) === false)。如果您需要相反的内容,请使用if (strpos(...) !== false)
  • 当我这样做时,它只返回我不希望它返回的结果,除了当我们将 true 设置为 false 时显示的内容之外,我需要所有内容,这就是问题所在。 .
  • 你甚至可以做到(!!strpos(...))..Example
  • @JohnDoe 使用大小写 in-sensitive 版本 -> if (stripos($n,'http://www.example.com/?dl_name=') !== FALSE) {..
【解决方案2】:

问题出在这里:

strpos($n,'http://www.example.com/?dl_name=') !== true

strpos 永远不会返回true,只有FALSE 不存在,或者它出现的第一个位置。你说你想要包含"http://www.example.com/?dl_name="的字符串对吧?

尝试将其更改为strpos($n,'http://www.example.com/?dl_name=') !== FALSE,看看会发生什么。

【讨论】:

  • 它提供的输出与设置 true 时的输出相同。到目前为止,我已经修改了大约 2 个小时,但到目前为止还没有运气。
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2016-09-01
  • 2012-07-11
  • 2018-04-08
  • 2017-04-20
  • 2018-10-02
  • 2016-09-04
相关资源
最近更新 更多