首页 > 解决方案 > 如何从数组中的网页中提取所有 URL 并查看是否存在某个值

问题描述

我正在尝试从网页中提取所有链接并将它们放入一个数组中,然后我可以比较值以查看是否匹配。我遇到的问题是我似乎无法将值放入数组中。我能够看到所有链接,并且我看到与我尝试比较的链接存在匹配,但它没有认识到它在那里。我的代码如下。任何帮助将不胜感激。

$content = file_get_contents("sample_url");
$content = strip_tags($content, "<a>");
$subString = preg_split("/<\/a>/", $content);
$items = array();
foreach ( $subString as $val ){
  if( strpos($val, "<a href=") !== FALSE ) {
    $val = preg_replace("/.*<a\s+href=\"/sm", "", $val);
    $val = preg_replace("/\".*/", "", $val);
    $items[] = $val;
    var_dump($val . "<br />");
  }
}

if (in_array($testing_link, $items, true)) {
  echo 'It is here!';
}
else {
  echo 'it is NOT here :( ';
}

标签: arrays

解决方案


最好使用 DOMDocument 将链接放入数组中。像这样:

$doc = new DOMDocument();
// the string containing all the URLs and stuff
$doc->loadHTML($content);
//Extract the links from the HTML. From https://thisinterestsme.com/php-find-links-in-html/
$links = $doc->getElementsByTagName('a');

//Array that will contain our extracted links.
$extracted_links = array();

//Loop through the DOMNodeList.
//We can do this because the DOMNodeList object is traversable.
foreach ($links as $link) {
  //Get the link text.
  //$linkText = $link->nodeValue;
  //Get the link in the href attribute.
  $linkHref = $link->getAttribute('href');
}

现在所有的 HREFS 都在$linkHref数组中。

最好使用 DOMDocument 而不是 RegEx。结果更容易,更准确和一致。


推荐阅读