php+curl+正则匹配,php curl 正则获取网页标题

/****/

//Gary xu

[email protected]

/****/

namespace Xuyaoxiang;

class Snoopy {

public $pattern_array=array(

‘title‘=>‘/

(\s*.*)/i‘,

‘description‘=>‘//‘,

‘charset‘=>‘/charset=\"?([\w-]+)\"?/i‘,

);

public $user_agent=‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36‘; //模拟浏览器头部数据

public $target_code="utf-8"; //目标编码

public $url;

public $data;

public $pattern_key;

function __construct($url)

{

$this->url=$url;

}

public function set_pattern($key,$val)

{

$this->pattern_array[$key]=$val;

}

function get_content($pattern_key)

{

$this->pattern_key=$pattern_key;

if($this->pattern_key==‘‘){return false;}

$this->curl_get_data();

if($this->data==false){return false;}

$charset=$this->get_charset();

$this->check_charset($charset);

$content=$this->get_key_content();

return trim($content[1]);

}

function curl_get_data()

{

$curl=curl_init();

// 设置你需要抓取的URL

curl_setopt($curl, CURLOPT_URL, $this->url);

// 设置header

curl_setopt($curl, CURLOPT_HEADER, 0);

// 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);

// 运行cURL,请求网页

$this->data = curl_exec($curl);

curl_close($curl);

}

function check_charset($page_charset)

{

if($page_charset!=$this->target_code)

{

$this->data=mb_convert_encoding($this->data,$this->target_code,$page_charset);

}

}

function get_key_content()

{

preg_match($this->pattern_array[$this->pattern_key],$this->data,$content);

return $content;

}

function get_charset()

{

preg_match($this->pattern_array[‘charset‘],$this->data,$reg_charset);

return $page_charset=strtolower($reg_charset[1]);

}

}

header("Content-type:text/html;charset=utf-8");

$snoopy=new snoopy("http://www.qq.com");

$title=$snoopy->get_content(‘title‘);

print_r($title);

?>

原文:http://www.cnblogs.com/xuyaoxiang/p/5485373.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值