arrays - 如何从数组中的网页中提取所有 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 :( ';
}
解决方案
最好使用 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。结果更容易,更准确和一致。
推荐阅读
- kotlin - PeriodicWorkRequest 不重复
- python - PySpark where 子句条件条件
- c# - 在 IIS 上的已发布应用程序中,每次我重新启动服务器或更改应用程序配置中的某些内容时,都会卸载项目引用
- java - 需要澄清 Oracle 教程解释何时使用迭代器与 for-each 构造
- android - android:停止通知振动
- angular - 角度可选 mat-optgroup
- python-3.x - 如何解决 webrtcvad.Error:处理帧时出错?
- java - java.lang.OutOfMemoryError:无法在 Windows 中创建新的本地线程 ..recreate
- c - 这个 c 程序 null 安全吗?
- python - 熊猫多索引,删除条件仍然成立的行?