function.php

4 篇文章 0 订阅

目录

函数方法

一、获取数组的并集

二、生成订单号

三、二维数组排序

四、获取域名http / https

五、判断身份证是否合法

六、身份证年龄、生日

七、浏览器名称和版本

八、时间戳-字符串输出,xxx秒前

九、计算两点地理坐标之间的距离

十、获取某月的最后一天

十一:数字转Excel的列字母组合

十二:多文件、字符串打包zip下载

十三、订单号生成

 十四、数组范围并集

字符串处理

一、验证邮箱格式

 二、将一个字符串部分字符用*替代隐藏

 三、根据汉字获取首字母(偏僻字无效)

 四、获取全局唯一标识符Guid

五、计算字符串长度(忽略字节)

六、字符串加密​​​​​​​

        七、图片连接补协议

图片处理

一、缩略图

二、生成验证码

三、添加水印

获取base64图片信息

导出Excel

Help

Nigix配置


函数方法

一、获取数组的并集

<?php

/**
 * 并集区间
 * @param array $a 区间a  [1,2]  | [1,2]  |  [1,2]              |   [2,5]
 * @param array $b 区间b  [2,4]  | [0,5]  |   [3,4]             |   [3,4]
 * @return array         [[1,4]]  |  [[0,5]]  |  [[1,2],[3,4]]  |   [[2,5]]
 */
function unionSection(array $a , array $b):array
{
	// 排序
	sort($a);
	sort($b);

	if($a[0] == $b[0]){
		// 情况1  [1,2] ∪ [1,4]  =  [[1,4]]  当第一位相同,则比较第二位
		if($a[1] > $b[1]){
			return [  [$a[0] , $a[1]]  ];
		}else{
			return [  [$a[0] , $b[1]]  ];
		}
		return [$result];

	}elseif($a[0] < $b[0]){
		// 情况2  
		if($a[1] == $b[0]){
			// [1,4] ∪ [4,6]  =  [[1,6]]
			return  [   [$a[0] , $b[1]]   ];
		}elseif($a[1] < $b[0]){
			// [1,4] ∪ [5,6]  =  [[1,4],[5,6] ]
			return  [   [$a[0] , $a[1]] , [$b[0] , $b[1]]   ];
			
		}elseif($a[1] > $b[0] ){
			// [1,4] ∪ [3,6]  =  [[1,6] ]
			// [1,5] ∪ [2,4]  =  [[1,5] ]
			if($a[1] > $b[1]){
				return  [   [$a[0] , $a[1]]   ];
			}else{
				return  [   [$a[0] , $b[1]]   ];
			}
		}
	}elseif($a[0] > $b[0]){

		// 情况3 
		if($a[0] == $b[1]){
			// [2,4] ∪ [0,2]  =  [[0,4]]
			return  [   [$b[0] , $a[1]]   ];
		}elseif($a[0] < $b[1]){
			// [2,4] ∪ [0,6]  =  [ [0,6] ]
			// [2,4] ∪ [0,3]  =  [ [0,4 ] ]
			if($a[1] > $b[1]){
				return  [   [$b[0] , $a[1]]   ];
			}else{
				return  [ [$b[0] , $b[1]] ];
			}
		}elseif($a[0] > $b[1]){
			// [2,4] ∪ [0,1]  =  [[0,1] , [2,4] ]
			return  [   [$a[0] , $a[1]] , [$b[0] , $b[1]]   ];
		}
	}
}

// 获取两个数组 数值上的并集
//  数组A:------1------------------4----->
//  数组B:------------2------------------5--------->
// 结果:  ------1------------------------5------>

// 如:
unionSection([1,2],[5,6]); //输出:[[1,2],[5,6]]
unionSection([1,5],[3,6]); //输出:[[1,6]]
unionSection([2,3],[1,6]); //输出:[[1,6]]

二、生成订单号

<?php
/**
 * 生订单号
 * @param string 前缀
 */
function create_order_num($ext = ''){
    return $ext.date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 8, 13), 1))), 0, 8);  //订单号
}
echo create_order_num();

三、二维数组排序

<?php
/**
 * 二维数组排序
 * @param array $arr 要排序的数组
 * @param string $col_key $arr 根据哪一列
 * @param string $sort_type desc:降序 asc:升序
 * @param string $sort_key_type 排序类型 SORT_NUMERIC|SORT_STRING
 */
function array_multi_sort($arr , $col_key , $sort_type = 'desc' , $sort_key_type = SORT_NUMERIC){
	$type = SORT_DESC;
	if($sort_type == 'asc'){
		$type = SORT_ASC;
	}
	$col_arr = array_column($arr, $col_key);
	array_multisort($col_arr,$sort_key_type, $type ,$arr );
	// array_multisort($col1_arr,$sort_key_type, $type ,$col2_arr, $sort_key_type, $type ,$arr );
	return $arr;
}

$arr = [
	[
		'id' => 1,
		'name' => '张1',
		'age' => 28
	],
	[
		'id' => 3,
		'name' => '张3',
		'age' => 21
	],
	[
		'id' => 2,
		'name' => '张2',
		'age' => 23
	],
	[
		'id' => 8,
		'name' => '张8',
		'age' => 13
	],
	[
		'id' => 3,
		'name' => '张4',
		'age' => 17,
	],
];
echo "<pre />";
var_dump(array_multi_sort($arr,'age','asc'));
// array(5) {
//   [0]=>
//   array(3) {
//     ["id"]=>
//     int(8)
//     ["name"]=>
//     string(4) "张8"
//     ["age"]=>
//     int(13)
//   }
//   [1]=>
//   array(3) {
//     ["id"]=>
//     int(3)
//     ["name"]=>
//     string(4) "张4"
//     ["age"]=>
//     int(17)
//   }
//   [2]=>
//   array(3) {
//     ["id"]=>
//     int(3)
//     ["name"]=>
//     string(4) "张3"
//     ["age"]=>
//     int(21)
//   }
//   [3]=>
//   array(3) {
//     ["id"]=>
//     int(2)
//     ["name"]=>
//     string(4) "张2"
//     ["age"]=>
//     int(23)
//   }
//   [4]=>
//   array(3) {
//     ["id"]=>
//     int(1)
//     ["name"]=>
//     string(4) "张1"
//     ["age"]=>
//     int(28)
//   }
// }

四、获取域名http / https

<?php
/**
 * 获取域名
 */
function get_domain(){
    
    $http_type = 'http://';
    if((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')){
    	$http_type = 'https://';
    }
    return $http_type . $_SERVER['HTTP_HOST'];
}

var_dump(get_domain());

五、判断身份证是否合法

<?php
/**
 * 判断是否为合法的身份证号码
 * @param string $idCard  身份证
 * @return boolean 是否是身份证
 */
function is_card_no($idCard){
    $vCity = array(
        '11','12','13','14','15','21','22',
        '23','31','32','33','34','35','36',
        '37','41','42','43','44','45','46',
        '50','51','52','53','54','61','62',
        '63','64','65','71','81','82','91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $idCard))
        return false;

    if (!in_array(substr($idCard, 0, 2), $vCity)) 
        return false;

    $idCard = preg_replace('/[xX]$/i', 'a', $idCard);
    $vLength = strlen($idCard);

    if ($vLength == 18) {
        $vBirthday = substr($idCard, 6, 4) . '-' . substr($idCard, 10, 2) . '-' . substr($idCard, 12, 2);
    } else {
        $vBirthday = '19' . substr($idCard, 6, 2) . '-' . substr($idCard, 8, 2) . '-' . substr($idCard, 10, 2);
    }

    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) 
        return false;

    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17 ; $i >= 0 ; $i--) {
            $vSubStr = substr($idCard, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
        }
        if($vSum % 11 != 1) 
            return false;
    }
    return true;
}

六、身份证年龄、生日

<?php
/**
 * 身份证输出年龄
 * @param string $idCard  身份证
 * @param boolean $isage  是否输出年龄
 * @return int  年龄 / 年月日
 */
function  to_card_age($idCard ,$isage = true){
    //获取当前年份;
    $now_year   = date('Y');
    //获取当前年份月份;
    $now_month  = substr(date('m'),0,1)=='0'  ? substr(date('m'),-1) : date('m');
    //获取当前日期;
    $now_day    = substr(date('d'),0,1)=='0'  ? substr(date('d'),-1) : date('d');
    if(strlen($idCard)==18){ 
        //18位身份证号;
        //获取身份证号对应的年,月份,日期;
        $card_year  = substr($idCard,6,4);
        //获取身份证号对应月份
        $card_month = substr($idCard,10,2);
        $card_month = substr($card_month,0,1)=='0' ? substr($card_month,-1): $card_month;
        //获取身份证号对应日期;
        $card_day   = substr($idCard,12,2);
        $card_day   = substr($card_day,0,1)=='0' ? substr($card_day,-1): $card_day;
     }else{  
        //15位身份证号;
        //获取身份证号对应的年,月份,日期;
        $card_year  = '19'.substr($idCard,6,2);

        //获取身份证号对应月份
        $card_month = substr($idCard,8,2);
        $card_month = substr($card_month,0,1)=='0' ? substr($card_month,-1): $card_month;

        //获取身份证号对应日期;
        $card_day   = substr($idCard,10,2);
        $card_day   = substr($card_day,0,1)=='0' ? substr($card_day,-1): $card_day;
    }
    if(!$isage){
        // 输出出生年月日
        return $card_year.'-'.$card_month.'-'.$card_day;
    }
    //获取当前年份和身份证年份之差;
    $age = $now_year - $card_year;

    $realAge = 0;
    if($now_month == $card_month){
        //比较日期;
        if($now_day >= $card_day){
           $realAge = $age;
        }else{
           $realAge = $age -1;        
        }
    }elseif($now_month > $card_month){
        $realAge =  $age;
    }else{
        $realAge = $age -1 ;
    }
    return  $realAge;
}

七、浏览器名称和版本

<?php
/**
 * 获取浏览器名称和版本
 * @return string
 */
function get_client_browser()
{
    if(empty($_SERVER['HTTP_USER_AGENT'])){
        return 'robot!';
    }
    if( (false == strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident')!==FALSE) ){
        return 'Internet Explorer 11.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 10.0')){
        return 'Internet Explorer 10.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 9.0')){
        return 'Internet Explorer 9.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 8.0')){
        return 'Internet Explorer 8.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 7.0')){
        return 'Internet Explorer 7.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 6.0')){
        return 'Internet Explorer 6.0';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'Edge')){
        return 'Edge';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'Firefox')){
        return 'Firefox';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'Chrome')){
        return 'Chrome';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'Safari')){
        return 'Safari';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'Opera')){
        return 'Opera';
    }
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'360SE')){
        return '360SE';
    }
    //微信浏览器
    if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessage')){
        return 'MicroMessage';
    }
    return '';
}

var_dump(get_client_browser());

八、时间戳-字符串输出,xxx秒前

<?php
/**
 * 时间戳-字符串输出,xxx秒前
 * @param int $time 时间戳
 * @return string
 */
function format_date_str(int $time)
{
    $t = time() - $time;
    $f = array(
        '31536000' => '年',
        '2592000' => '个月',
        '604800' => '星期',
        '86400' => '天',
        '3600' => '小时',
        '60' => '分钟',
        '1' => '秒'
    );
    foreach ($f as $k => $v) {
        if (0 != $c = floor($t / (int)$k)) {
            return $c . $v . '前';
        }
    }
}
var_dump(format_date(1658959234)); // 4分钟前

九、计算两点地理坐标之间的距离

<?php
/**
     * 计算两点地理坐标之间的距离
     * @param  $longitude1 起点经度
     * @param  $latitude1 起点纬度
     * @param  $longitude2 终点经度 
     * @param  $latitude2 终点纬度
     * @param Int   $unit    单位 1:米 2:公里
     * @param Int    精度 保留小数位数
     * @return 
     */
    function get_distance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){
    
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;
    
        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;
    
        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;
    
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
    
        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;
    
        if($unit==2){
            $distance = $distance / 1000;
        }
    
        return round($distance, $decimal);
    
    }

十、获取某月的最后一天

<?php
/**
 * 获取某月的最后一天
 * @param int $year 年
 * @param int $month 月
 * @return string
 */
function get_month_last_day(int $year , int $month){
	return date('d',strtotime($year.'-'.$month.'-01 +1 month -1 day' ));

// switch ($month) {
//         case 4 :
//         case 6 :
//         case 9 :
//         case 11 :
//             $days = 30;
//             break;
//         case 2 :
//         if ($year % 4 == 0) {
//             if ($year % 100 == 0) {
//                 $days = $year % 400 == 0 ? 29 : 28;
//             } else {
//                 $days = 29;
//             }
//         } else {
//             $days = 28;
//         }
//         break;
//         default :
//             $days = 31;
//             break;
//     }
//     return $days;
// }
}
var_dump(get_month_last_day(2022,3)); // 31

十一:数字转Excel的列字母组合

<?php
/**
 * 获取数字列的英文编码 
 * @param $num  int 数字
 * @return string 返回Excel的列编码
 */
function _getEcode($num , $code_list = []){
    // if(!$code_list){
    //     $code_list = range('A','Z');
    // }
    $num --;
    $str = ''; 
    $sum = intval($num / 26);
    if ($sum > 0) { 
        $str .= _getEcode($sum , $code_list); 
    }
    // return $str . $code_list[$num % 26];
    return $str . chr($num % 26 + 65); // acsii
}

var_dump(_getEcode(1)); // A
var_dump(_getEcode(27)); // AA
var_dump(_getEcode(702)); // ZZ

十二:多文件、字符串打包zip下载

<?php
/**
     * 下载
     * @param array $file_path_arr  文件路径数组
     * [
     *      [
     *          'file_name' => '',  // 文件名称
     *          'file_path' => '',  // 文件路径或者地址
     *          'file_type' => '', // 文件类型 : base64 
     *      ]
     * ]
     * @param string $download_name  下载名称
     */
    public static function run($file_path_arr , $download_name , $app_id)
    {
        //在此之前你的项目目录中必须新建一个空的zip包
        $file_template = public_path().'download_zip_temp.zip';
        if(!file_exists($file_template)){
            throw new \Exception('download_zip_temp.zip文件不存在');
        }
        //即将打包的zip文件名称
        $downname = $download_name.'.zip';
        //把你打包后zip所存放的目录
        $file_name = public_path().'temp\\'.$app_id.'\\'.$downname;
        if(!file_exists(public_path().'temp\\'.$app_id.'\\')){
            // 文件加不存在,创建文件夹
            if(!mkdir(public_path().'temp\\'.$app_id.'\\' , 777 , true)){
                throw new \Exception('文件创建失败');
            }
        }
        //把原来项目目录存在的zip复制一份新的到另外一个目录并重命名(可以在原来的目录)
        $result = copy($file_template, $file_name);
        if(!$result){
            throw new \Exception('文件创建失败');
        }
        $zip=new \ZipArchive();
        //打开你复制过后空的zip,包在zip压缩包中建一个空文件夹,成功时返回 TRUE
        if($zip->open($file_name,\ZipArchive::CREATE)===TRUE){
            //根据自己的场景需要去处理业务
            foreach($file_path_arr as $val){
                if($val['file_type'] == 'base64'){
                    // 图片base64 类型
                    $zip->addFromString($val['file_name'].'.'.get_base64img_info($val['file_path'] , 'type'),base64_decode(explode(',',$val['file_path'])[1]));
                }else{
                    $zip->addFromString($val['file_name'].'.txt',$val['file_path']);
                }
            }
            $zip->close();
            $fp=fopen($file_name,"r");
            //获取文件的字节
            $file_size=filesize($file_name);
            //下载需要的header头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".$file_size);
            Header("Content-Disposition: attachment; filename=$downname");
            //设置一次读取的字节数,每读取一次,就输出数据(即返回给浏览器)
            $buffer=102400000; // 100m
            //读取的总字节数
            $file_count=0;
            //向浏览器返回数据,如果下载完成就停止输出
            while(!feof($fp) && $file_count<$file_size){
                $file_con=fread($fp,$buffer);
                $file_count+=$buffer;
                echo $file_con;
            }
            fclose($fp);
            //下载完成后删除压缩包,临时文件夹
            if($file_count>=$file_size){
                unlink($file_name);
            }
            return true;
        }
    }

十三、订单号生成

/**
 * 生成订单号
 */
function create_order_no($exp = 'A')
{
    return $exp.date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

 十四、数组范围并集


$a  = [5,7];
$b  = [2,4];

/**
 * 并集区间
 * @param array $a 区间a  [1,2]  | [1,2]  |  [1,2]              |   [2,5]
 * @param array $b 区间b  [2,4]  | [0,5]  |   [3,4]             |   [3,4]
 * @return array         [[1,4]]  |  [[0,5]]  |  [[1,2],[3,4]]  |   [[2,5]]
 */
function unionSection(array $a , array $b):array
{
	// 排序
	sort($a);
	sort($b);

	if($a[0] == $b[0]){
		// 情况1  [1,2] ∪ [1,4]  =  [[1,4]]  当第一位相同,则比较第二位
		if($a[1] > $b[1]){
			return [  [$a[0] , $a[1]]  ];
		}else{
			return [  [$a[0] , $b[1]]  ];
		}
		return [$result];

	}elseif($a[0] < $b[0]){
		// 情况2  
		if($a[1] == $b[0]){
			// [1,4] ∪ [4,6]  =  [[1,6]]
			return  [   [$a[0] , $b[1]]   ];
		}elseif($a[1] < $b[0]){
			// [1,4] ∪ [5,6]  =  [[1,4],[5,6] ]
			return  [   [$a[0] , $a[1]] , [$b[0] , $b[1]]   ];
			
		}elseif($a[1] > $b[0] ){
			// [1,4] ∪ [3,6]  =  [[1,6] ]
			// [1,5] ∪ [2,4]  =  [[1,5] ]
			if($a[1] > $b[1]){
				return  [   [$a[0] , $a[1]]   ];
			}else{
				return  [   [$a[0] , $b[1]]   ];
			}
		}
	}elseif($a[0] > $b[0]){

		// 情况3 
		if($a[0] == $b[1]){
			// [2,4] ∪ [0,2]  =  [[0,4]]
			return  [   [$b[0] , $a[1]]   ];
		}elseif($a[0] < $b[1]){
			// [2,4] ∪ [0,6]  =  [ [0,6] ]
			// [2,4] ∪ [0,3]  =  [ [0,4 ] ]
			if($a[1] > $b[1]){
				return  [   [$b[0] , $a[1]]   ];
			}else{
				return  [ [$b[0] , $b[1]] ];
			}
		}elseif($a[0] > $b[1]){
			// [2,4] ∪ [0,1]  =  [[0,1] , [2,4] ]
			return  [   [$a[0] , $a[1]] , [$b[0] , $b[1]]   ];
		}
	}

}

字符串处理

一、验证邮箱格式

/**
 * 是否是邮箱
 * @param string $email 邮箱地址
 * @return string|boolean  邮箱格式返回邮箱,非邮箱则返回 false
 */
function is_email(string $email){
  return filter_var($email, FILTER_VALIDATE_EMAIL);
}
var_dump(is_email('admin@cc.cc'));  // 输出admin@cc.cc

 二、将一个字符串部分字符用*替代隐藏

<?php

/**
 +----------------------------------------------------------
 * 将一个字符串部分字符用*替代隐藏
 +----------------------------------------------------------
 * @param string $string 待转换的字符串
 * @param int  $bengin 起始位置,从0开始计数,当$type=4时,表示左侧保留长度
 * @param int  $len  需要转换成*的字符个数,当$type=4时,表示右侧保留长度
 * @param int  $type  转换类型:0,从左向右隐藏;1,从右向左隐藏;2,从指定字符位置分割前由右向左隐藏;3,从指定字符位置分割后由左向右隐藏;4,保留首末指定字符串
 * @param string $glue  分割符
 +----------------------------------------------------------
 * @return string 处理后的字符串
 +----------------------------------------------------------
 */
function hide_str(string $string, int $bengin = 0, int $len = 4, int $type = 0, string $glue = "@") {
	if (empty($string))
		return false;
	$array = array();
	if ($type == 0 || $type == 1 || $type == 4) {
		$strlen = $length = mb_strlen($string);
		while ($strlen) {
			$array[] = mb_substr($string, 0, 1, "utf8");
			$string = mb_substr($string, 1, $strlen, "utf8");
			$strlen = mb_strlen($string);
		}
	}
	if ($type == 0) {
		for ($i = $bengin; $i < ($bengin + $len); $i++) {
			if (isset($array[$i]))
				$array[$i] = "*";
		}
		$string = implode("", $array);
	} else if ($type == 1) {
		$array = array_reverse($array);
		for ($i = $bengin; $i < ($bengin + $len); $i++) {
			if (isset($array[$i]))
				$array[$i] = "*";
		}
		$string = implode("", array_reverse($array));
	} else if ($type == 2) {
		$array = explode($glue, $string);
		$array[0] = hide_str($array[0], $bengin, $len, 1);
		$string = implode($glue, $array);
	} else if ($type == 3) {
		$array = explode($glue, $string);
		$array[1] = hide_str($array[1], $bengin, $len, 0);
		$string = implode($glue, $array);
	} else if ($type == 4) {
		$left = $bengin;
		$right = $len;
		$tem = array();
		for ($i = 0; $i < ($length - $right); $i++) {
			if (isset($array[$i]))
				$tem[] = $i >= $left ? "*" : $array[$i];
		}
		$array = array_chunk(array_reverse($array), $right);
		$array = array_reverse($array[0]);
		for ($i = 0; $i < $right; $i++) {
			$tem[] = $array[$i];
		}
		$string = implode("", $tem);
	}
	return $string;
}
 
// 电话号码隐藏
$str = '12345678901'; // 电话号码
echo hide_str($str,4,4);   //输出 1234****901

// 姓名隐藏
$str = '诸葛三丰';
echo hide_str($str,1,1);  //诸*三丰
$str = '张三丰';
echo hide_str($str,1,1);  //张*丰
$str = '张三';
echo hide_str($str,1,1);  //张*
$str = '张';
echo hide_str($str,1,1);  //张

// 特殊隐藏
$str = 'admin@cc.cc';
echo hide_str($str,1,1,0,'@');  //a*min@cc.cc
echo hide_str($str,1,1,1,'@');  //admin@cc.*c
echo hide_str($str,1,1,2,'@');  //adm*n@cc.cc
echo hide_str($str,1,1,3,'@');  //admin@c*.cc
echo hide_str($str,1,1,4,'@');  //a*********c

 三、根据汉字获取首字母(偏僻字无效)

偏僻字:php获取中文拼音(含生僻字)支持首字母,全拼_冯伪猿的博客-CSDN博客_php 获取中文拼音

<?php
/**
 * 获取汉字的首字母
 * 获取单个汉字拼音首字母。注意:此处不要纠结。汉字拼音是没有以U和V开头的
 * @param string 文字
 * @return string
 */
function getfirstchar($s0){   
    $fchar = ord($s0{0});
    if($fchar >= ord("A") and $fchar <= ord("z") ) 
    	return strtoupper($s0{0});
    $s1 = iconv("UTF-8","gb2312", $s0);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $s0){
    	$s = $s1;
    }else{
    	$s = $s0;
    }
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if($asc >= -20319 and $asc <= -20284) return "A";
    if($asc >= -20283 and $asc <= -19776) return "B";
    if($asc >= -19775 and $asc <= -19219) return "C";
    if($asc >= -19218 and $asc <= -18711) return "D";
    if($asc >= -18710 and $asc <= -18527) return "E";
    if($asc >= -18526 and $asc <= -18240) return "F";
    if($asc >= -18239 and $asc <= -17923) return "G";
    if($asc >= -17922 and $asc <= -17418) return "H";
    if($asc >= -17922 and $asc <= -17418) return "I";
    if($asc >= -17417 and $asc <= -16475) return "J";
    if($asc >= -16474 and $asc <= -16213) return "K";
    if($asc >= -16212 and $asc <= -15641) return "L";
    if($asc >= -15640 and $asc <= -15166) return "M";
    if($asc >= -15165 and $asc <= -14923) return "N";
    if($asc >= -14922 and $asc <= -14915) return "O";
    if($asc >= -14914 and $asc <= -14631) return "P";
    if($asc >= -14630 and $asc <= -14150) return "Q";
    if($asc >= -14149 and $asc <= -14091) return "R";
    if($asc >= -14090 and $asc <= -13319) return "S";
    if($asc >= -13318 and $asc <= -12839) return "T";
    if($asc >= -12838 and $asc <= -12557) return "W";
    if($asc >= -12556 and $asc <= -11848) return "X";
    if($asc >= -11847 and $asc <= -11056) return "Y";
    if($asc >= -11055 and $asc <= -10247) return "Z";
    return '';
}

var_dump(getfirstchar('张三')); // Z

 四、获取全局唯一标识符Guid

<?php
/**
 * 获取全局唯一标识符
 * @param bool $trim
 * @return string
 */
function get_guid($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        $charid = com_create_guid();
        return $trim == true ? trim($charid, '{}') : $charid;
    }
    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    // Other
    $charid = strtolower(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);
    $guidv4 = substr($charid, 6, 2).substr($charid, 4, 2).
    substr($charid, 2, 2).substr($charid, 0, 2).$hyphen
    .substr($charid, 10, 2).substr($charid, 8, 2).$hyphen
    .substr($charid, 14, 2).substr($charid, 12, 2).$hyphen
    .substr($charid, 16, 4). $hyphen .substr($charid, 20, 12);
    return $guidv4;
}

var_dump(get_guid());  // 输出:59d54e09-fa24-43c9-a661-a57b2699fe89

五、计算字符串长度(忽略字节)

<?php
/**
 * 计算文字、英文、数字长度
 * @param string $str 
 */
function count_str($str){
    $str = str_replace(' ', '', $str);
    $str = preg_replace('/[\x80-\xff]{1,3}/', ' ', $str, -1);   
    return strlen($str);
}
echo count_str('治丧.、‘;、】【'); // 9
echo count_str('张三'); // 2
echo count_str('zhangsan'); // 8

六、字符串加密

<?php

/**
 * 隐私工具
 */
class PrivacyUtil{

    // 密钥
	public  $key = '1234567891234567';  // 默认的key

	/**
	 * 字符置换
	 */
	const MAP_ARR = [
		'1' => '0', '2' => '2', '3' => '4', '4' => '6', '5' => '7', '6' => '1', '7' => '3', '8' => '9', '9' => '8', '0' => '5' ,
		'a' => 'q', 'b' => 'w', 'c' => 'e', 'd' => 'r', 'e' => 't', 'f' => 'y', 'g' => 'u', 'h' => 'i', 'i' => 'o', 'j' => 'p', 'k' => 'a', 
		'l' => 's', 'm' => 'd', 'n' => 'f', 'o' => 'g', 'p' => 'h', 'q' => 'j', 'r' => 'k', 's' => 'l', 't' => 'z', 'u' => 'x', 'v' => 'c',
		'w' => 'v',	's' => 'b',	'y' => 'n',	'z' => 'm',
		'A' => 'M', 'B' => 'N', 'C' => 'B', 'D' => 'V', 'E' => 'C', 'F' => 'X', 'G' => 'Z', 'H' => 'A', 'I' => 'S', 'J' => 'D', 'K' => 'F',
		'L' => 'G', 'M' => 'H', 'N' => 'J', 'O' => 'K', 'P' => 'L', 'Q' => 'P', 'R' => 'O', 'S' => 'I', 'T' => 'U', 'U' => 'Y', 'V' => 'T',
		'W' => 'R', 'S' => 'E', 'Y' => 'W', 'Z' => 'Q'
	];

	// 初始化
	public function __construct(){
		$key = config('edoprivacy.key');
		if($key){
			$this->key = $key;
		}
	}
	/**
	 * 加密
	 */
	public function encryption($string){
        if(!$string){
            return '';
        }
		// 字符互换
		$string = $this->strSwap($string ,'encryption');
        // 加盐
        $string = openssl_encrypt($string, 'AES-128-ECB', $this->key, 0);  
		// 输出
		return $string;
	}
	/**
	 * 解密
	 */
	public function decryption($string){
        if(!$string){
            return '';
        }
        // 解密
        $string = openssl_decrypt($string, 'AES-128-ECB', $this->key, 0); 
		
		// // 字符互换
		$string = $this->strSwap($string , 'decryption');
		// 输出
		return $string;
	}
	/**
	 * 字符交换
	 */
	public function strSwap($str , $op){
		$map_arr = [];
		if($op == 'decryption'){
			// 获取交换数组
			$map_arr = array_flip(self::MAP_ARR);
		}elseif($op == 'encryption'){
			$map_arr = self::MAP_ARR;
		}
		$res_str = '';
		for ($i=0; $i < strlen($str); $i++) { 
			if(isset($map_arr[$str[$i].''])){
				$res_str .= $map_arr[$str[$i].''];
			}else{
				$res_str .= $str[$i];
			}
		}
		return $res_str;
	}
}

七、图片连接补协议

/**
 * 图片补全
 * @author Yel 
 * @param $url    string  地址
 * @param $domain string  域名
 */
function tomedia($url = '', $domain = 'https://www.baidu.com/'){
    // 验证 url 是否是  http://  或者  https://  或者  // 开头
    if ((substr($url, 0, 7) == 'http://') || (substr($url, 0, 8) == 'https://') || (substr($url, 0, 2) == '//')) {
        return $url;
    }
    return $domain.$url;
}

// 测试
var_dump(tomedia('https://asdasd'));
echo '<br>';
var_dump(tomedia('asdasd'));
echo '<br>';

//结果
string(14) "https://asdasd" 
string(28) "https://www.baidu.com/asdasd" 

图片处理

PHP简单的实现图像处理 - 知乎

Grafika文档

一、缩略图

<?php
/**
 * 缩略图
 * extension=php_gd2.dll
 * window : 修改php.ini文件,删除 extension=php_gd2.dll 前面的;开启图像处理支持。
 * centos : yum install php-gd*
 * ubuntu : apt-get install php7.3-gd
 */
class Resize
{
	/**
	 * 初始化
	 */
	public function __construct(){
		// 检测是否开启GD 扩展
		if(!extension_loaded('GD')){
			throw new \Exception('请安装GD扩展');
		}
	}

	/**
	 * 生成
	 * @param string $file 源文件
	 * @param string $to 保存文件  如填null则直接输出
	 * @param int $width 缩略图宽度 
	 * @param int $height 缩略图高度 
	 * @param int $type 缩略图类型 1:固定宽度,高度自动 2:高度固定,宽度自动  3:固定宽度,高度裁切
	 * @return bool
	 */
    public function make(string $file, string $to = null, int $width = 200, int $height = 200, int $type = 3)
    {
    	// 获取图片资源
        $image = $this->resource($file);
        // 获取检查信息  imagesx($image) : 获取宽度  imagesy($image):获取高度
        $info = $this->size($width, $height, imagesx($image), imagesy($image), $type);
        // 创建画布
        $res = imagecreatetruecolor($info[0], $info[1]);
        //图片缩放
        imagecopyresampled($res, $image, 0, 0, 0, 0, $info[0], $info[1], $info[2], $info[3]);
        
        $result = false;
        if($to){
        	// 保存缩略图
        	$result = imagejpeg($res ,$to);	
        }else{
        	// 输出缩略图
        	header('Content-type:image/jpeg');
        	$result = imagejpeg($res);
        }
        // 释放图片资源
        imageDestroy($res);
        imageDestroy($image);
        // 返回信息
        return $result;
    }

   	/**
   	 * 获取尺寸
   	 */
    protected function size($rw, $rh, $iw, $ih, int $type)
    {
        switch ($type) {
            case 1:
                //固定宽度,高度自动
                $rh = $rw / $iw * $ih;
                break;
            case 2:
                //高度固定,宽度自动 
                $rw = $rh / $ih * $iw;
                break;
            case 3:
                //固定宽度,高度裁切
                $ih = $iw / $rw * $rh;
                break;
            default:
                if (($iw / $rw) > ($ih / $rh)) {
                    $iw = $ih / $rh * $rh;
                } else {
                    $ih = $iw / $rw * $rw;
                }
        }
        return [$rw, $rh, $iw, $ih];
    }

    /**
     * 把原图片转化为画布资源
     */
    protected function resource(string $image)
    {
 
    	// 检测文件是否存在  是否是图片文件
		$info = getimagesize($image);
        if ($info === false) {
            throw new \Exception("文件不存在或非图片");
        }

        $functions = [
        	1 => 'imagecreatefromgif', 
        	2 => 'imagecreatefromjpeg', 
        	3 => 'imagecreatefrompng'
        ];

        if(!isset($functions[$info[2]])){
        	throw new \Exception('暂只支持:jpeg、png、gif');
        }
        
        $call = $functions[$info[2]];
        return $call($image);
    }
}

$Resize = new Resize();
// $Resize->make('https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg',null,200,200,3);
$Resize->make('text.jpeg',null,100,100,3);

二、生成验证码

<?php

class Captcha
{
    protected $width;  // 宽度
    protected $height;  // 高度
    protected $res;  // 图片资源
    protected $len = 4;  // 验证吗数字
    protected $font;  // 字体
    protected $size;  // 字体尺寸
    /**
     * 初始化
     * @param int $width 宽度
     * @param int $height 高度
     * @param int $size 字体尺寸
     */
    public function __construct(int $width = 100, int $height = 30, $size = 20)
    {
    	if(!extension_loaded('GD')){
    		throw new Exception("请开启GD扩展");
    	}
        $this->width = $width;
        $this->height = $height;
        $this->font = realpath('stheitisc.ttf'); // 网上下载字体即可
        $this->size = $size;
    }

    /**
     * 输出二维码
     */
    public function make()
    {
    	// 创建画布
        $res = imagecreatetruecolor($this->width, $this->height);
        // 设置 rgb(200,200,200) 的颜色填充到 $res 画布资源
        imagefill($this->res = $res, 0, 0, imagecolorallocate($res, 200, 200, 200));
        // 设置验证码
        $this->text();
        $this->line();
        $this->pix();
        $this->render();
    }
    /**
     * 在画布中设置文字
     */
    protected function text()
    {
    	// 预设文字
        $text = 'abcdefghigk123456789';
        // 长度
        for ($i = 0; $i < $this->len; $i++) {

        	// 设置文字的位置
            $x = $this->width / $this->len * $i;
            // 设置文本盒子,文本占用位置的大小
            $box = imagettfbbox($this->size, 0, $this->font, $text[$i]);
            // 给画布设置文案
            imagettftext(
                $this->res,  // 资源
                $this->size,  // 字体尺寸
                mt_rand(-20, 20),  // 角度
                $x,  // x 点
                $this->height / 2 + ($box[0] - $box[7]) / 2, // y点
                $this->textColor(),  // 颜色
                $this->font, // 字体
                strtoupper($text[rand(0,19)]) // 设置大写随机获取文字
            );
        }
    }
    /**
     * 绘制随机点像素(噪点)
     */
    protected function pix()
    {	
    	// 300 个噪点
        for ($i = 0; $i < 300; $i++) {
            imagesetpixel(
                $this->res,  // 画布
                mt_rand(0, $this->width), // x轴
                mt_rand(0, $this->height),  // y轴
                $this->color()  // 颜色
            );
        }
    }
    /**
     * 设置 随机线
     */
    protected function line()
    {
    	//  6条随机线
        for ($i = 0; $i < 6; $i++) {
        	// 设置像素的厚度
            imagesetthickness($this->res, mt_rand(1, 3));
            // 划线
            imageline(
                $this->res, // 画布
                mt_rand(0, $this->width), // x起点
                mt_rand(0, $this->height), // y起点
                mt_rand(0, $this->width),  // x终点
                mt_rand(0, $this->height),  // y终点
                $this->color() // 设置颜色
            );
        }
    }
    // 设置颜色
    protected function color()
    {
        return imagecolorallocate($this->res, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));
    }
    // 设置文字颜色
    protected function textColor()
    {
        return imagecolorallocate($this->res, mt_rand(50, 150), mt_rand(50, 150), mt_rand(50, 150));
    }
    // 输出 png 图片
    protected function render()
    {
        header('Content-type:image/png');
        imagepng($this->res);
    }
}

$Captcha = new Captcha(200,50,20);
$Captcha->make();

三、添加水印

<?php

class Water
{
    //水印资源
    protected $water;
    //水印图片
    public function __construct(string $water)
    {
        $this->water = $water;
    }
    
    /**
     * @param string $image 原图片
     * @param string $filename 保存图片
     * @param int $pos 水印位置
     */
    public function make(string $image, string $filename = null, int $pos = 9)
    {	
    	// 获取图片资源
        $res = $this->resource($image);
        // 创建水印画布
        $water = $this->resource($this->water);
        // 获取位置
        $postion = $this->position($res, $water, $pos);
        // 把水印复制到 原图上
        imagecopy(
        	$res, 
        	$water,  
        	$postion['x'], 
        	$postion['y'], 
        	0, 
        	0, 
        	imagesx($water), 
        	imagesy($water)
        );
       	//输出
        $this->showAction($image)($res , $filename?:$filename);
    }
    /**
     * 获取原图图片,设置成画布
     * @param 文件路径
     */
    protected function resource($image)
    {
    	// 获取原图尺寸
        $info = getimagesize($image);
        $function = [1 => 'imagecreatefromgif', 2 => 'imagecreatefromjpeg', 3 => 'imagecreatefrompng'];
        $call = $function[$info[2]];
        // 根据图片类型使用对应的方法
        return $call($image);
    }
    /**
     * 输出图片
     */
    protected function showAction(string $image)
    {
    	// 获取原图尺寸
        $info = getimagesize($image);
        // 根据类型输出对应的图片
        $function = [1 => 'imagegif', 2 => 'imagejpeg', 3 => 'imagepng'];
        return $function[$info[2]];
    }
    /**
     * 设置水印的位置
     */
    protected function position($des,  $res, int $pos)
    {
        $info = ['x' => 0, 'y' => 0];
        switch ($pos) {
            case 1:
            	// 左上角
                break;
            case 2:
            	// 中上
                $info['x'] = (imagesx($des) - imagesx($res)) / 2;
                break;
            case 3:
            	// 右上角
                $info['x'] = (imagesx($des) - imagesx($res));
                break;
            case 4:
            	//左中
                $info['y'] = (imagesy($des) - imagesy($res)) / 2;
                break;
            case 5:
            	// 中间
                $info['x'] = (imagesx($des) - imagesx($res)) / 2;
                $info['y'] = (imagesy($des) - imagesy($res)) / 2;
                break;
            case 6:
            	// 右中
                $info['x'] = (imagesx($des) - imagesx($res));
                $info['y'] = (imagesy($des) - imagesy($res)) / 2;
                break;
            case 7:
            	// 左下
                $info['y'] = (imagesx($des) - imagesx($res));
                break;
            case 8:
            	// 中下
            	$info['x'] = (imagesx($des) - imagesx($res)) / 2;
                $info['y'] = (imagesx($des) - imagesx($res));
                break;
            default:
            	// 右下
            	$info['x'] = (imagesx($des) - imagesx($res));
                $info['y'] = (imagesx($des) - imagesx($res));
                break;
        }
        return $info;
    }
}
// 
$image =  new Water('1.jpeg');
header('Content-type:image/jpg');
$image->make('https://vimsky.com/wp-content/uploads/2020/02/046d7bc7d5f6db6a466faf888a04639a.jpg','des.jpg',9);

获取base64图片信息

<?php
/**
 * 获取 base64 图片信息
 */
function get_base64img_info($base64img,$type = 'type'){

    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64img, $result)){
        if ($type=='type'){
            $img_result = $result[2];
        }elseif ($type=='size'){
            $base_img = str_replace($result[1], '', $base64img);
            $base_img = str_replace('=','',$base_img);
            $img_len = strlen($base_img);
            $file_size = intval($img_len - ($img_len/8)*2);
            $img_result = number_format(($file_size/1024),2);//KB
        }
        return $img_result;
    }
}

导出Excel

<?php

// 获取扩展包
require './vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

/**
 * 导出
 * 安装:composer require phpoffice/phpspreadsheet
 */
class Export{
    
    private $list= [];// 列表数据
    private $header = []; // 头数据
    private $title = '未定义'; // 标题
    private $model = null;  // Spreadsheet 对象
    private $sheet = null; // xlsx的sheet
    //数字对应的英文(基础)
    private $e = [];
    // 行号
    private $row_index = 0;
    /**
     * 初始化
     * @param array  $header 需要导出的数据 $header = [ 'ID','name','age' ];
     * @param array  $list 需要导出的数据 $list = [ [1,'张三',18], [2,'李四',19]];
     * @param string $title 文件名
     */
    function __construct(array $header = [], array $list = [] ,string $title = '未定义' ){
        $this->header = $header;
        $this->list = $list;
        $this->title = $title;

        $this->model = new Spreadsheet();
        $this->sheet = $this->model->getActiveSheet();
        // 获取 26 个英文字母
        $this->e = range('A','Z');
        //设置标题
        $this->setTitle();
        // 设置列名
        $this->setHeader();
        //设置内容
        $this->_setData();
    }

    /**
     * 导出
     */
    public function run(){
        //保存文件
        $writer = new Xlsx($this->model);
        //文件名
        $filename = iconv("UTF-8","GB2312//IGNORE", $this->title). '-' . date('YmdHis') . '.xlsx';
        // 头
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        // 获取缓冲区数据
        if($error_msg = ob_get_contents()){
            // 清空并关闭缓冲区
            ob_end_clean(); // 如果不清空缓冲,则在php 警告时,导出的文件时有问题的
        }
        //输出
        $writer = IOFactory::createWriter($this->model, 'Xlsx');
        $writer->save('php://output');
    }

    //---------------------------------
    //|  获取工作簿 start
    //---------------------------------
    /**
     * 获取工作簿
     */
    public function getSheet(){
        return $this->sheet;
    }
    //---------------------------------
    //|  获取工作簿 end
    //---------------------------------

    //---------------------------------
    //|  设置标题 start
    //---------------------------------
    /**
     * 设置标题
     */
    public function setTitle(){
        $this->sheet->setTitle($this->title);
    }
    //---------------------------------
    //|  设置标题 end
    //---------------------------------

    //---------------------------------
    //|  设置头行 start
    //---------------------------------
    /**
     * 设置列名
     */
    public function setHeader(){
        $this->row_index ++;
        foreach ($this->header as $key => $value) {
            $this->sheet->setCellValue($this->_getEcode($key + 1).$this->row_index,$value);
        }
    }
    //---------------------------------
    //|  设置头行 end
    //---------------------------------

    //---------------------------------
    //|  设置内容 start
    //---------------------------------
    /**
     * 设置内容
     */
    private function _setData(){
        // 循环添加列
        foreach ($this->list as $key => $row) {
            // 添加行
            $this->addRow($row);
        }
    }
    /**
     * 追加行
     * @param array $row 向excel表追加一列
     */
    public function addRow(array $row , bool $is_add_list = false){
        $this->row_index ++;
        $i = 0;
        foreach ($row as $k => $v) {
            // 获取单元格位置 
            $cell = $this->_getEcode($i + 1).$this->row_index;
            $i ++;
            // 给单元格设置值
            $this->setCellValue($cell , $k , $v);
        }
        // 是否追加到列表
        if($is_add_list){
            $this->list[] = $row;    
        }
    }
    /**
     * 设置内容
     */
    public function setCellValue($cell ,$key , $value){
        // 当value等于数组,则可能设置了样式
        if(is_array($value)){
            $style = $value;
            if(isset($style['style'])){
                $style = $value['style'];
                $key = $value['value']?:$value[0];
            }
            // 是否设置了样式
            $is_style = false;
            // 设置了字体颜色
            if(isset($style['bg_color'])){
                $this->setCellBgColor($cell,$style['bg_color']);
                $is_style = true;
            }
            if(isset($style['font_color'])){
                $this->setCellFontColor($cell,$style['font_color']);
                $is_style = true;
            }
            if($is_style){
                $value = $key;
            }
        }
        // 把 内容写入 位置 如 A2
        $this->sheet->setCellValue($cell, "\t".$this->_setRowData($value)."\t");
    }

    /**
     * 获取设置范围值
     * @param string $place 合并范围  $this->getCells() 的返回值
     */
    public function setStyle(string $place , array $config = []){
        // 获取区域值
        foreach ($config as $key => $value) {
            switch ($key) {
                case 'bg_color':
                    $this->setCellBgColor($place , $value);
                    break;
                case 'font_color':
                    $this->setCellFontColor($place , $value);
                    break;
                default:
                    # code...
                    break;
            }
        }
    }
    
    //---------------------------------
    //|  设置内容 end
    //---------------------------------
   
   	//---------------------------------
    //|  行数 end
    //---------------------------------
    /**
     * 设置行号
     */
    public function setRowIndex(int $row){
        $this->row_index = $row;
    }
    /**
     * 获取行号
     */
    public function getRowIndex(){
        return $this->row_index;
    }
    //---------------------------------
    //|  行数 end
    //---------------------------------

    //---------------------------------
    //|  字体 start
    //---------------------------------
    /**
     * 设置字体
     * @param string $place 合并范围  $this->getCells() 的返回值
     * @param string $name 字体名称
     */
    public function setFontName(string $place , string $name = 'Arial'){
    	$this->sheet->getStyle($place)->getFont()->setName($name);
    }

    /**
     * 字体加粗
     * @param string $place 合并范围  $this->getCells() 的返回值
     */
    public function setFontBold(string $place){
    	$this->sheet->getStyle($place)->getFont()->setBold(true);
    }

    /**
     * 字体大小
     * @param string $place 合并范围  $this->getCells() 的返回值
     * @param int $size 字体大小
     */
    public function setFontSize(string $place , int $size = 10){
    	$this->sheet->getStyle($place)->getFont()->setSize(true);
    }
    //---------------------------------
    //|  字体 end
    //---------------------------------

    //---------------------------------
    //|  颜色 start
    //---------------------------------
    /**
     * 给某个单元格文字设置颜色
     * @param string $place 合并范围  $this->getCells() 的返回值
     * @param string $color 颜色 : #000000
     */
    private function setCellFontColor(string $place , $color){
        // 去掉#号
        $color = str_replace('#', '', $color);
        if(strlen($color) >= 8){
            $this->sheet->getStyle($place)->getFont()->getColor()->setARGB($color);
        }else{
            $this->sheet->getStyle($place)->getFont()->getColor()->setRGB($color);
        }
    }

    /**
     * 给某个单元格设置背景颜色
     * @param string $place 合并范围  $this->getCells() 的返回值
     * @param string $color 颜色 : #000000
     */
    private function setCellBgColor($place , $color){
        // 去掉#号
        $color = str_replace('#', '', $color);
        // 给单元格文字设置颜色
        if(strlen($color) >= 8){
            $this->sheet->getStyle($place)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB($color);
        }else{
            $this->sheet->getStyle($place)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($color);    
        }
    }
    //---------------------------------
    //|  颜色 end
    //---------------------------------

    //---------------------------------
    //|  列 start
    //---------------------------------
    /**
     * 设置列宽度
     * @param $col  int 列数
     * @param $width int 宽度 
     */
    public function setWidth(int $col , int $width = -1){
        //列
        $col = intval($col);
        if($col < 0)
            throw new \Exception('setWidth 方法参数错误!设置列必须大于0的整数!');
        // 有宽则设置固定宽 , 否则自动宽度
        if($width > 0){
        	// 设置列的
        	$this->sheet->getColumnDimension($this->_getEcode($col))->setWidth($width);
        }else{
        	$this->sheet->getColumnDimension($this->_getEcode($col))->setAutoSize(true);
        }
    }
    //---------------------------------
    //|  列 end
    //---------------------------------

    //---------------------------------
    //|  行 start
    //---------------------------------
    /**
     * 自动换行
     * 设置某一列自动换行
     * @param int $col 列数
     */
    public function autoHeight($col){
        $this->sheet->getStyle($this->_getEcode($col))->getAlignment()->setWrapText(true);
    }

    /**
     * 设置默认行高
     * @param int $height 行高度
     * @param int $row_index 某一行的高度,否则全部行高
     */
    public function setRowHeight(int $height = 15 , $row_index = -1){
    	if($row_index > 0){
    		$this->sheet->getRowDimension($row_index)->setRowHeight($height);
    	}else{
    		$this->sheet->getDefaultRowDimension()->setRowHeight($height);
    	}
    }
    //---------------------------------
    //|  行 end
    //---------------------------------

    //---------------------------------
    //|  水平居中对齐 start
    //---------------------------------
    /**
     *水平居中对齐
     * @param string $place 合并范围  $this->getCells() 的返回值
     */
    public function fontCenter(string $place){
    	$styleArray = [
	    	'alignment' => [
	        	'horizontal' => Alignment::HORIZONTAL_CENTER,
		    ],
		];
		$this->sheet->getStyle($place)->applyFromArray($styleArray);
    }
    //---------------------------------
    //|  水平居中对齐 end
    //---------------------------------
    //---------------------------------
    //|  单元格合并 start
    //---------------------------------
    /**
     * 单元格合并
     * @param string $place 合并范围  $this->getCells() 的返回值
     */
    public function setMergeCells(string $place){
        // 合并
        $this->sheet->mergeCells($place);
    }
    //---------------------------------
    //|  单元格合并 end
    //---------------------------------

    //---------------------------------
    //|  边框 start
    //---------------------------------
    /**
     * 给特定区域设置边框
     * @param string $place 合并范围  $this->getCells() 的返回值
     */
    public function setBorder(string $place){
        $styleArray1 = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $this->sheet->getStyle($place)->applyFromArray($styleArray1);
    }

    /**
     * 设置带颜色的边框
     * @param string $place 合并范围  $this->getCells() 的返回值
     * @param string $color 颜色 : #000000
     */
    public function setColorBorder(string $place ,string $color){
    	// 去掉#号
        $color = str_replace('#', '', $color);
    	$styleArray = [
		    'borders' => [
		        'outline' => [
		            'borderStyle' => Border::BORDER_THICK,
		            'color' => ['argb' => $color],
		        ],
		    ],
		];
		 $this->sheet->getStyle($place)->applyFromArray($styleArray);
    }
    //---------------------------------
    //|  边框 end
    //---------------------------------
    
    //---------------------------------
    //|  日期 start
    //---------------------------------
    /**
     * 设置日期格式
     * @param int $col 列数
     */
    public function setValueDate(int $col){
    	$this->sheet->getStyle($this->_getEcode($col))->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD);
    }
    //---------------------------------
    //|  日期 end
    //---------------------------------
    

    /**
     * 获取单元格区域
     * @param int $start_row 开始行
     * @param int $start_col  结束列     
     * @param int $end_row  结束行 默认等于开始行
     * @param int $end_col  结束列 默认等于开始列
     */
    public function getCells(int $start_row , int $start_col ,int $end_row = null,int $end_col = null){
        if(!$end_row){
            $end_row = $start_row;
        }
        if(!$end_col){
            $end_col = $start_col;
        }
        $left_top = $this->_getEcode($start_col).$start_row;
        $right_buttom = $this->_getEcode($end_col).$end_row;

        $place = $left_top.':'.$right_buttom;
        return $place;
    }

    /**
     * 根据数据格式输出对应内容
     */
    private function _setRowData($v){
        if(is_numeric($v) || is_string($v)){
            return $v;
        }
        if(is_array($v)){
            return json_encode($v,true);
        }
        if(is_callable($v)){
            return $this->_setRowData($v());
        }
        throw new \Exception('导出数据格式错误!');
    }

    /**
     * 获取数字列的英文编码 
     * @param $num  int 列数
     * @return string 返回Excel的列编码
     */
    private function _getEcode($num){
        $num --;
        $str = ''; 
        $sum = intval($num / 26);
        if ($sum > 0) { 
            $str .= $this->_getEcode($sum); 
        }
        return $str . $this->e[$num % 26]; 
    }

}
// //标题
// $title = '测试';
// //表头
// $header = [ 'ID','姓名','内容' ];
// //导出内容
// $list = [ 
//     //数字
//     [1,'张22222222222222222222222222222222三',18], 
//     //数组
//     [3,'王五',[2,3,4]], 
//     //自定义导出格式1
//     [4,'赵六',function() use ($title){
//         return '今年29岁';  //返回数组或字符串
//     }], 
//     // 自定义导出格式1
//     [
//         5,
//         [
//             'value' => function(){
//                 return '我是王刚';
//             },
//             'style' => [
//                 'font_color' => '#FF0180'
//             ]
//         ],
//         '29岁'
//     ], 
// ];
// // //实例化
// $Export = new Export($header,$list,$title);
// // 设置边框 从第二行 第二列开始   结束于  第11行第11列
// $Export->setBorder($Export->getCells(2,2,11,11));

// //设置第二列宽度
// $Export->setWidth(26);
// // 设置 从第1行 第1列开始   结束于  第1行第1列 的字体颜色 、 背景颜色
// $Export->setStyle($Export->getCells(1,1,5,5) ,[
//     'bg_color' => '#dc6c6c',
//     'font_color' => '#FF0180'
// ]);
// // 增加1行
// $Export->addRow([
//     6  => [
//         'bg_color' => '#444444',
//     ],
//     '123123',
//     '19岁'
//     ]);
// // 空开 5行
// $Export->setRowIndex($Export->getRowIndex() + 5);

// // 设置 从第8行 第1列开始   结束于  第12行第3列 的背景颜色
// $Export->setStyle($Export->getCells(8,1,12,3 ),[
//     'bg_color' => '#dc6c6c'
// ]);

// // 合并
// $Export->setMergeCells($Export->getCells(8,1,13,1));
// // 合并
// $Export->setMergeCells($Export->getCells(8,2,13,2));
// // 合并
// $Export->setMergeCells($Export->getCells(8,3,13,3));
// // 空开 5行
// $Export->setRowIndex($Export->getRowIndex() + 5);
// // 增加1行
// $Export->addRow([7,function(){
//         return '我是王刚';
//     },'29岁']);

// // 合并
// $Export->setMergeCells($Export->getCells(9,1,11,1));
// // 自动高度
// $Export->autoHeight(2);
// //导出
// $Export->run();

Help

Nigix配置

# 禁止访问  {url}/index.php/admin/ 入口
location ^~ /index.php/admin/ {  
     # 禁止访问 
     return 403;
}


# 图片跨域
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
   #允许跨域请求
    add_header Access-Control-Allow-Origin '*';
    add_header Access-Control-Allow-Headers X-Requested-With;
    add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

    expires 30d;
    access_log off;
  }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值