下面是一个函数,用于验证.edu TLD并检查url是否未指向.pdf文档或.doc文档。
public function validateEduDomain($url) {
if( preg_match('/^https?:\/\/[A-Za-z]+[A-Za-z0-9\.-]+\.edu/i', $url) && !preg_match('/\.(pdf)|(doc)$/i', $url) ) {
return TRUE;
}
return FALSE;现在我遇到了指向simple_html_dom试图解析并返回其内容的jpg、rtf和其他格式的链接。我想通过跳过所有这样的链接来避免这种情况的发生。问题是这个列表不是详尽的,我希望代码跳过所有这样的链接。我该怎么做??
发布于 2012-01-02 01:08:11
尝试通过猜测urls背后的内容来过滤urls在许多情况下总是会失败。假设您使用curl进行下载,您应该检查响应文档类型标头是否在可接受的标头中:
<?php
require "simple_html_dom.php";
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //default is to output it
$urls = array(
"google.com",
"https://www.google.com/logos/2012/newyearsday-2012-hp.jpg",
"http://cran.r-project.org/doc/manuals/R-intro.pdf",
);
$acceptable_types = array("text/html", "application/xhtml+xml");
foreach ($urls as $url) {
curl_setopt($curl, CURLOPT_URL, $url);
$contents = curl_exec($curl);
//we need to handle content-types like "text/html; charset=utf-8"
list($response_type) = explode(";", curl_getinfo($curl, CURLINFO_CONTENT_TYPE));
if (in_array($response_type, $acceptable_types)) {
echo "accepting {$url}\n";
// create a simple_html_dom object from string
$obj = str_get_html($contents);
} else {
echo "rejecting {$url} ({$response_type})\n";
}
}运行上述命令会产生以下结果:
accepting google.com
rejecting https://www.google.com/logos/2012/newyearsday-2012-hp.jpg (image/jpeg)
rejecting http://cran.r-project.org/doc/manuals/R-intro.pdf (application/pdf)发布于 2012-01-02 00:51:30
将最后一个正则表达式更新为如下所示:
!preg_match('/\.(pdf)|(doc)|(jpg)|(rtf)$/i', $url) )将过滤出jpgs和rtf文档。
您必须将扩展名添加到上面的正则表达式中以省略它们。
更新
我不认为阻止所有类型的扩展是可能的,我个人也不推荐它用于抓取使用。你将不得不跳过一些扩展来继续爬行。为什么不将正则表达式筛选器更改为您愿意接受的筛选器,如下所示:
preg_match('/\.(html)|(html)|(php)|(aspx)$/i', $url) )https://stackoverflow.com/questions/8694233
复制相似问题