<?php
header("Content-type: text/html; charset=utf-8");
/**
* $url web url
* $data HTML data if $url set to false
* $type return data type,can be:
0 所有<a>标签。
1 所有href。
2 所有带http(s)://链接。
3 所有域名,如:www.cnblogs.com。
4 所有a标签内容
* @ example
echo '<pre>'; //这句加了看起来会好看些(*^__^*)
var_dump(getWebLinks('
http://www.php100.com'));
var_dump(getWebLinks('
http://www.php100.com',1));
var_dump(getWebLinks('
http://www.php100.com',2));
var_dump(getWebLinks('
http://www.php100.com',3));
var_dump(getWebLinks('
http://www.php100.com',4));
*/
function getWebLinks($url=false,$type=0,$data=false){
if(!empty($url)){
$data =
@file_get_contents( 'http://' . str_replace('http://','',$url) );
}
//页面编码判定及转码
$charset_pos = stripos($data,'charset');
if($charset_pos) {
if(stripos($data,'charset=utf-8',$charset_pos)) {
$data = iconv('utf-8','utf-8',$data);
}else if(stripos($data,'charset=gb2312',$charset_pos)) {
$data = iconv('gb2312','utf-8',$data);
}else if(stripos($data,'charset=gbk',$charset_pos)) {
$data = iconv('gbk','utf-8',$data);
}
}
//$pattern = '/<a(?:[\s\S]*?)href\s*?=\s*?[\'"]([^\"\']*)[\'"][\s\S]*?<\/a>/i'; //仅href
$pattern = '/<a(?:[\s\S]*?)href\s*?=\s*?[\'"](((?:http(?:s?):\/\/)?([^\"\'\/]+))?(?:[^\"\']*))[\'"](?:[^>]*?)>([\s\S]*?)<\/a>/i';
preg_match_all($pattern, $data, $links);
return $links[(int)$type];
}
//End_php