错误时strpos仍返回

时间:2018-08-17 19:24:11

标签: php function strpos

$post_id = 228;

$content_post = get_post($post_id);
$content = $content_post->post_content;


$doc = new DOMDocument();
$doc->loadHTML($content);

$links = $doc->getElementsByTagName('a');

foreach ($links as $link){
    $href = $link->getAttribute('href');
    $avoid  = array('.jpg', '.png', '.gif', '.jpeg');

    if (strpos($href, $avoid) == false) {
        echo $link->nodeValue, '<br>';
        echo $href, '<br>';
    }
}

strpos仍在返回false时返回网址-知道我丢失了什么吗? !==也不起作用。

添加的信息:我正在尝试排除所有图片网址,因此,如果您有更好的方法,请随时分享。

更新,也无法解决问题。 (使用文档对此进行了尝试)。

    foreach ($links as $link){
    $href = $link->getAttribute('href');
    $avoid  = array('.jpg', '.png', '.gif', '.jpeg');
    $pos = strpos($href, $avoid);

    if ($pos === false) {

    echo $link->nodeValue, '<br>';
    echo $href, '<br>';
   }
   }

2 个答案:

答案 0 :(得分:5)

如果要检查$href中是否包含$avoid中的任何字符串,可以将它们替换为空,以查看是否仍然有原始字符串。

if ($href == str_replace($avoid, '', $href)) { ...

str_replace可以采用数组,与strpos不同。

答案 1 :(得分:2)

Warning: strpos(): needle is not a string or an integer。使用其他方式,例如preg_match:

$href = 'aaa.jpeg';
preg_match('/(\.jpg|\.png|\.gif|\.jpeg)/', $href, $matches);

var_dump($matches);

if(empty($matches)) {
    //not match...
}