php函数

/**
 * 正则应用:匹配字符串中第一张图片
 * preg_match_all(正则规则,要匹配检索的对象,存储匹配结果的数组)
 * array_slice(数组,开始位置,返回的长度)
 */
function getImg($data,$num=1){
	$pattern = "/<img.*?src=[\'|\"](.+?)[\'|\"].*?>/si";
	preg_match_all($pattern,  stripslashes($data),$match);
	if(!empty($match) && !empty($match[1])){
		return $num == 1?$match[1][0]:array_slice($match[1],0,$num);
	}else{
		return $num == 1?'http://www.baidu.com/uploads/defaultpic.jpg':'';
	}
}

/**
 *正则应用:匹配字符串中的所有图片
 *@param type $content 内容
 */
function getImgs($content, $order = 'ALL') {
	$pattern = "/<img.*?src=[\'|\"](.+?)[\'|\"].*?>/si";
	preg_match_all ( $pattern, $content, $match );
	if (isset($match[1]) && !empty($match[1])) {
		if ($order === 'ALL'){
			return $match[1];
		}
		if (is_numeric($order) && isset($match[1][$order])) {
			return $match[1][$order];
		}
	}
	return '';
}

/**
 * 去除文章中图片的宽高,让其自适应
 * @parram $content 含有图片的字符串
 * @parram $s 要搜索的模式
 * @parram $r 用于替换的字符串或字符串数组
 */
function get_replace($content){
	$s = array('/(<img.*?)(width=\".*?\")(.*?>)/is','/(<img.*?)(height=\".*?\")(.*?>)/is','/(<img.*?)(style=\".*?\")(.*?>)/is');
	$r = array('\1\3','\1\3','\1\3');
	$str = preg_replace($s, $r, $content);
	return $str;
}

/**
 *使用CURL抓取页面,代替file_get_contents
 *@param type $url 地址
 */
function get_tao_img($url){
	$ch = curl_init();
	//特殊情况  CURLOPT_ENCODING => 'gzip'如果目标网站启用了gzip,则在客户端自动解压
	curl_setopt($ch, CURLOPT_URL, $url);
	//curl_setopt($ch, CURLOPT_HEADER, TRUE);    //表示需要response header
	curl_setopt($ch, CURLOPT_NOBODY, FALSE); //表示需要response body
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
	curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	$result = curl_exec($ch);
	$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
	if($httpCode==200){
		echo '请求成功';
	}elseif($httpCode==404){
		echo '请求地址为404页面';
	}else{
		echo "其他错误".$httpCode;
	}
	return $result;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值