php提取网页超链接 邮箱及其它内容的实现代码

发布时间:2019-07-22编辑:脚本学堂
专门用于提取网页所有超链接,邮箱及其它指定内容的php代码,供大家学习参考。

完整代码如下。

<?php
/**
 * 提取网页超链接 邮箱等内容
 * by http://www.jb200.com
*/
function fetch_urlpage_contents($url){
$c=file_get_contents($url);
return $c;
}
//获取匹配内容
function fetch_match_contents($begin,$end,$c)
{
$begin=change_match_string($begin);
$end=change_match_string($end);
$p = "#{$begin}(.*){$end}#iU";//i表示忽略大小写,U禁止贪婪匹配
if(preg_match_all($p,$c,$rs))
{
return $rs;}
else { return "";}
}//转义正则表达式字符串
function change_match_string($str){
//注意,以下只是简单转义
$old=array("/","$",'?');
$new=array("/","$",'?');
$str=str_replace($old,$new,$str);
return $str;
}

//采集网页
function pick($url,$ft,$th)
{
$c=fetch_urlpage_contents($url);
foreach($ft as $key => $value)
{
$rs[$key]=fetch_match_contents($value["begin"],$value["end"],$c);
if(is_array($th[$key]))
{ foreach($th[$key] as $old => $new)
{
$rs[$key]=str_replace($old,$new,$rs[$key]);
}
}
}
return $rs;
}

$url="http://www.yourdomain.com"; //要采集的地址
$ft["a"]["begin"]='<a'; //截取的开始点<br />
$ft["a"]["end"]='>'; //截取的结束点

$rs=pick($url,$ft,$th); //开始采集
print_r($rs["a"]);
?>