PHP常用函数

php 专栏收录该内容
59 篇文章 0 订阅
<?php
header('Content-Type: text/html; charset=utf-8');//设置字符集
/*
 * 都报出来: error_reporting(11);
  不要报NOTICE: error_reporting(3);
  任何错误都不报: error_reporting(0);
系统为我们把各个级别的值,用系统常量代替了.

    E_ERROR 1
    E_WARNING 2
    E_NOTICE 8
报所有错误: error_reporting(E_ALL);

除了NOTICE,其他都报: error_reporting(E_ALL & ~E_NOTICE);
E_WARNING,其他都报: error_reporting(E_ALL & ~E_WARNING);
*/
error_reporting(E_ALL ^ E_NOTICE ^E_WARNING);//设置错误提示级别

//打印的p函数
function p($arr){
    return "<pre>".print_r($arr)."<pre/>";
}

//冒泡排序;
function maopao($data){
    $len=count($data);
    if($len<1){
        return $data;
    }
    $count=count($data);
        for($i=0;$i<$count;$i++){
          for($j=$count-1;$j>$i;$j--){
              if($data[$j]<$data[$j-1]){
                  $tmp=$data[$j];
                  $data[$j]=$data[$j-1];
                  $data[$j-1]=$tmp;
              }
          }
    }
    return $data;
}
//快速排序;
function paixu($arr){
    $count=count($arr);
    for($i=0;$i<$count;$i++){
        for($j=$i+1;$j<$count;$j++){
            if($arr[$i]>$arr[$j]){
                $tmp=$arr[$i];
                $arr[$i]=$arr[$j];
                $arr[$j]=$tmp;
            }
        }
    }
    return $arr;
}

//获取字符串的长度;
function str($str)
{
    $count = 0;
    while(1) {
        if ($str[$count] != NULL) {
            $count++;
            continue;
        }

        return $count;
    }
}
/*字符串的反转*/
function fanzhuan($str){
    $count=strlen($str);
    for($i=$count-1;$i>=0;$i--){
        $str .=$str[$i];
    }
    return $str;
}


/*随机产生字符串*/
function create_password($pw_length = 10)
{
    $randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
    $randpwd .= chr(mt_rand(33, 126));
}
return $randpwd;
}

/*随机产生字符串*/
function generate_password( $length = 8 ) {
// 密码字符集,可任意添加你需要的字符
    $chars ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
    $password ='';
for ( $i = 0; $i < $length; $i++ )
{
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符;
// 第二种是取字符数组 $chars 的任意元素
// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
    $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $password;
}

/*产生随机字符串*/
function sp_random_string($len = 6) {
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/*无限极分类*/
function limitless($data,$parent_id=0,$level){
    $arr=array();
    foreach ($data as $v){
        if($v['parent_id']==$parent_id){
            $v['level']=$level;
            $v['html']=str_repeat('|'.'---', ($level*1));
            $arr[]=$v;
            $arr=array_merge($arr,$this->limitless($data,$v['cid'],$level+1));
        }
    }
    return $arr;
}

/*无限极分类返回树形结构*/
 function category_tree($category,$parent=0){
    $arr=array();
    foreach($category as $v){
        if($v['parent'] == $parent){
            $v['sub_category']=category_tree($category,$v['term_id']);
            $arr[]=$v;
        }
    }
    return $arr;
}
/*给出时间戳算出是星期几*/
function getWeek($sDate){
    $iweek = date('N', strtotime($sDate));
    switch($iweek){
        case 7:
            return '星期日';
            break;
        case 1:
            return '星期一';
            break;
        case 2:
            return '星期二';
            break;
        case 3:
            return '星期三';
            break;
        case 4:
            return '星期四';
            break;
        case 5:
            return '星期五';
            break;
        case 6:
            return '星期六';
            break;
    }
}
/**
 *js弹出跳转
 *$string 弹出内容
 *$address 跳转地址
 *第二个参数不传默认转回当前地扯
 *用法:script('万普万岁','Wap/Mrugr/index')
 *@author 技术支持:张湘南
 **/
function script($string,$address,$get){
    if($address){
        if($string){
            echo '<script>alert("'.$string.'");location.href="'.U($address,$get).'"</script>';die;
        }else{
            echo '<script>location.href="'.U($address,$get).'"</script>';die;
        }
    }else{
        if($string){
            echo '<script>alert("'.$string.'");history.back();</script>';die;
        }else{
            echo '<script>history.back();</script>';die;
        }
    }
}
//给出两个日期算中间有多少个月分
//getMonthNum('2009-05-02','2009-07-03');
function getMonthNum($start,$end){
    $start=strtotime($start);
   // echo $start;
    $end=strtotime($end);
    //echo $end;
    $start_y=date('Y',$start);
    $start_m=date('m',$start);
    $start_d=date('d',$start);


    $end_y=date('Y',$end);
    $end_m=date('m',$end);
    $end_d=date('d',$end);
    $m=($end_y-$start_y)*12+$end_m-$start_m;
    if($end_d<=$start_d){
        $m=$m-1;
    }
    return $m;
}
//二维json数据转换成二维数组
function json2arr($json){
    $arr = array();
    foreach((array)$json as $key=>$val){
        if(is_object($val))$arr[$key] = json2arr($val);
        else $arr[$key] = $val;
    }
    return $arr;
}
$data=array('a','c','k','g','e','x','d','a','c');
$arr=array(23,5,26,4,9,85,10,2,55,44,21,39,11,16,55,88,421,226,588);
/**
 *删除有序数组中相同的元素
 *$array  二维数组
 *$string 子段
 *@author 技术支持:张湘南
 *用法:array_delete($list,'wg');
 **/
function array_delete2($array,$string){
    foreach ($array as $ke => $v){
        $array[$v[$string]][$string]=$v[$string];
        $array[$v[$string]]=$v;
        unset($array[$ke]);//删除原来的
    }
    unset($array['']);//删除键名为空的
    return $array;
}
//cookie实现最近浏览;
 function setRecentView(){
    $key = ('recent-view');
    $value = isset($_COOKIE[$key])?unserialize(base64_decode($_COOKIE[$key])):array();
    if(!in_array($this->gid,$value)){
        array_unshift($value, $this->gid);
    }
    setcookie($key,base64_encode(serialize($value)),time()+86400,'/');
}
//过滤网站敏感关键词
function cleanWords($text){
    $badword="日|死|靠|你妹";
    $badwords=explode('|',$badword);
    foreach($badwords as $v){
        $text=str_replace($v,"**",$text);
        //$text=str_replace($v,"<span style='color: red'>$v</span>",$text);//加上红色标记
    }
    return $text;
}
//判断内容中是否存在指定字符
function check_sensitive_words($content,$keyword){

    $keyword = split(',',$keyword);
    foreach($keyword as $key=>$value){
        if(strstr($content,$value)){
            return true;
        }
    }
}
/**
+----------------------------------------------------------
 * 对查询结果集进行排序
+----------------------------------------------------------
 * @access public
+----------------------------------------------------------
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
+----------------------------------------------------------
 * @return array
+----------------------------------------------------------
 */
$ary=array(
    array("ID"=>21,"name"=>"kitty"),
    array("ID"=>22,"name"=>"sony"),
    array("ID"=>17,"name"=>"picker"),
    array("ID"=>19,"name"=>"picker"));
function list_sort_by($list,$field, $sortby='desc') {
    if(is_array($list)){
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }

        foreach ( $refer as $key=> $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }

    return false;
}

print_r(list_sort_by($ary,'ID','nat'));

//获取一定范围内的随机数
function rand_number ($min, $max) {
    return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
}

//URL安全的字符串编码:
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}
//URL安全的字符串解码:
function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}
/**
 *
+--------------------------------------------------------------------
 * Description 友好显示时间
+--------------------------------------------------------------------
 * @param int $time 要格式化的时间戳 默认为当前时间
+--------------------------------------------------------------------
 * @return string $text 格式化后的时间戳
+--------------------------------------------------------------------
 * @author yijianqing
+--------------------------------------------------------------------
 */
function mdate($time = NULL) {
    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 (秒)
    if ($t == 0)
        $text = '刚刚';
    elseif ($t < 60)
        $text = $t . '秒前'; // 一分钟内
    elseif ($t < 60 * 60)
        $text = floor($t / 60) . '分钟前'; //一小时内
    elseif ($t < 60 * 60 * 24)
        $text = floor($t / (60 * 60)) . '小时前'; // 一天内
    elseif ($t < 60 * 60 * 24 * 3)
        $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
    elseif ($t < 60 * 60 * 24 * 30)
        $text = date('m月d日 H:i', $time); //一个月内
    elseif ($t < 60 * 60 * 24 * 365)
        $text = date('m月d日', $time); //一年内
    else
        $text = date('Y年m月d日', $time); //一年以前
    return $text;
}

/*函数Getx2x有四个参数:
第一个参数[必须]为表名;
第二个参数[必须]为字段名;
第三个参数[必须]为所查询字段的值。
第四个参数[可选]为所查询的字段名,未填默认为'id'。*/

//万能单条件查询函数,由lisan制作
function Getx2x($table,$fields,$id,$str){
    $aa=M($table);
    if(empty($str)){
        $expression='getByid';
    }else{
        $expression='getBy'.$str;
    }
    $thisaa=$aa->field($fields)->$expression($id);
    $bb=explode(',',$fields);
    if(count($bb)<=1){
        return $thisaa[$fields];
    }else{
        return $thisaa;
    }
}
//ip地址定位函数
function IP($ip='',$charset='gbk',$file='QQWry.dat') {
    static $_ip    =    array();
    if(isset($_ip[$ip])) {
        return $_ip[$ip];
    }else{
        import("ORG.Net.IpLocation");
        $iplocation =   new IpLocation($file);
        $location   =   $iplocation->getlocation($ip);
        $_ip[$ip]    =    $location['country'].$location['area'];
    }
    if('utf-8' != $charset) {
        $_ip[$ip] = iconv($charset,'utf-8',$_ip[$ip]);
    }
    return $_ip[$ip];
}
/**
 * 清空目录
 * @param string $path 目录路径
 * @param bool $rmdir 若为真,则删除目录本身
 * @return bool
 * @author  吾爱
 */
function qkdir($path,$rmdir=false){
    if(!is_dir($path)){
        return false;
    }
    if($handle=opendir($path)){
        while(false!==($item=readdir($handle))){
            if($item=="." || $item==".."){
                continue;
            }
            $item=rtrim($path,"/")."/".$item;
            if(is_dir($item)){
                qkdir($item);
                @rmdir($item);
                continue;
            }
            @unlink($item);
        }
        closedir($handle);//关闭句柄
    }
    if($rmdir){
        @rmdir($path);
    }
    return TRUE;
}

//颜色转换函数
 function hex2rgb( $colour ) {
     if ( $colour[0] == '#' ) {
         $colour = substr( $colour, 1 );
     }
     if ( strlen( $colour ) == 6 ) {
         list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
     } elseif ( strlen( $colour ) == 3 ) {
         list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
     } else {
         return false;
     }
     $r = hexdec( $r );
     $g = hexdec( $g );
     $b = hexdec( $b );
     return array( 'red' => $r, 'green' => $g, 'blue' => $b );
 }
//Author:铜豌豆
//QQ:309581329
//Email:bestphper@126.com
//http://gongwen.sinaapp.com
//史上产生位数最短的随机唯一ID
function getRandOnlyId() {
    //新时间截定义,基于世界未日2012-12-21的时间戳。
    $endtime=1356019200;//2012-12-21时间戳
    $curtime=time();//当前时间戳
    $newtime=$curtime-$endtime;//新时间戳
    $rand=rand(0,99);//两位随机
    $all=$rand.$newtime;
    $onlyid=base_convert($all,10,36);//把10进制转为36进制的唯一ID
    return $onlyid;
}
//得到随机唯一id
//echo getRandOnlyId();

//检查qq在线状态
$qqStr = '450031117:291277891:781787584:1585887008:10086:1035334740:8043198';
$qqArr = explode ( ':', $qqStr );
$qqArr = array_unique ( $qqArr );
sort ( $qqArr );
$qqStr = implode ( ':', $qqArr );
$url = 'http://webpresence.qq.com/getonline?Type=1&' . $qqStr . ':';
$html = file_get_contents ( $url );
$Arr = explode ( ']=', $html );
$count = count ( $Arr );
 for($i = 1; $i < $count; $i ++) {
     $result [$qqArr [$i - 1]] = substr ( $Arr [$i], 0, 1 );
 }

//获取链接中的参数和值
function getKeyValue($url) {
    $result = array();
    $mr = preg_match_all('/(\?|&)(.+?)=([^&?]*)/i', $url, $matchs);
    if ($mr !== FALSE) {
        for ($i = 0; $i < $mr; $i++) {
            $result[$matchs[2][$i]] = $matchs[3][$i];
        }
    }
    return $result;
}
//获取中文首字母
function getfirstchar($s0){
    $firstchar_ord=ord(strtoupper($s0{0}));
    if (($firstchar_ord>=65 and $firstchar_ord<=91)or($firstchar_ord>=48 and $firstchar_ord<=57)) return $s0{0};
    $s=iconv("UTF-8","gb2312", $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>=-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 null;
}

//带密匙的加密解密函数
function encrypt($data, $key)
{
    $key    =   md5($key);
    $x      =   0;
    $len    =   strlen($data);
    $l      =   strlen($key);
    $char='';
    $str='';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}

function decrypt($data, $key)
{
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    $char='';
    $str='';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
        {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }
        else
        {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}

/**
 * 字符串截取,支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}

//字符串转换成数组


/**
 **  输出多维数组函数
 * 将数组的值连接成字符串输出
 **/
function arr_foreach ($arr) {
    if (!is_array ($arr)) {
        return false;
    }
    foreach ($arr as $key => $val ) {
        if (is_array ($val)) {
            arr_foreach ($val);
        } else {
            echo $val;
        }
    }
    echo '<br/>';
}



//过滤函数过滤字符串
function _safe($str){
    $html_string = array("&", " ", "'", '"', "<", ">", "\t", "\r");
    $html_clear = array("&", " ", "'", """, "<", ">", "    ", "");
    $js_string = array("/<script(.*)<\/script>/isU");
    $js_clear = array("");
    $frame_string = array("/<frame(.*)>/isU", "/<\/fram(.*)>/isU", "/<iframe(.*)>/isU", "/<\/ifram(.*)>/isU",);
    $frame_clear = array("", "", "", "");
    $style_string = array("/<style(.*)<\/style>/isU", "/<link(.*)>/isU", "/<\/link>/isU");
    $style_clear = array("", "", "");
    $str = trim($str);
    //过滤字符串
    $str = str_replace($html_string, $html_clear, $str);
    //过滤JS
    $str = preg_replace($js_string, $js_clear, $str);
    //过滤ifram
    $str = preg_replace($frame_string, $frame_clear, $str);
    //过滤style
    $str = preg_replace($style_string, $style_clear, $str);
    return $str;

}
//过滤函数
function remove_html_tag($str){  //清除HTML代码、空格、回车换行符
    //trim 去掉字串两端的空格
    //strip_tags 删除HTML元素
    $str = trim($str);
    $str = @preg_replace('/<script[^>]*?>(.*?)<\/script>/si', '', $str);
    $str = @preg_replace('/<style[^>]*?>(.*?)<\/style>/si', '', $str);
    $str = @strip_tags($str,"");
    $str = @ereg_replace("\t","",$str);
    $str = @ereg_replace("\r\n","",$str);
    $str = @ereg_replace("\r","",$str);
    $str = @ereg_replace("\n","",$str);
    $str = @ereg_replace(" ","",$str);
    $str = @ereg_replace(" ","",$str);
    return trim($str);
}

//PHP防XSS 防SQL注入的代码
function gjj($str)
{
    $farr = array(
        "/\\s+/",
        "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
    );
    $str = preg_replace($farr,"",$str);
    return addslashes($str);
}

function hg_input_bb($array)
{
    if (is_array($array))
    {
        foreach($array AS $k => $v)
        {
            $array[$k] = hg_input_bb($v);
        }
    }
    else
    {
        $array = gjj($array);
    }
    return $array;
}
$_REQUEST = hg_input_bb($_REQUEST);
$_GET = hg_input_bb($_GET);
$_POST = hg_input_bb($_POST);

//返回当前时间的前一天后后一天
function times($data){
    $time = strtotime($data);
    $time = $time ? $time : time();//$time当前选定时间
    $a = -86400;//86400是一天的时间秒
    $aDate[]=date('Y-m-d',$time-86400);//当前选定时间的前一天
    $aWeek[] = getWeek($aDate[0]);
    for ($i=0; $i<2; $i++){
        $a+=86400;
        $aDate[] = $sDate=date('Y-m-d',$time+$a);
        $aWeek[] = getWeek($sDate);
    } //取得2天的时间
    return array('data'=>$aDate,'week'=>$aWeek);
}

//p(times('2015-11-18'));

//格式化时间函数
function t_date($time)
{
    return date('Y-m-d H:i:s', $time);
}
/**
 * 字符串转换为数组,主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
    return explode($glue, $str);
}

/**
 * 数组转换为字符串,主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
    return implode($glue, $arr);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {
    Vendor('PHPMailer.PHPMailer');
    $mail = new \vendor\PHPMailer\PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称(这里以QQ邮箱为例)
    $mail->SMTPAuth = true; //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址(也就是你的邮箱地址)
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(TRUE); // 是否HTML格式邮件
    $mail->CharSet='utf-8'; //设置邮件编码
    $mail->Subject =$title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
    return($mail->Send());
}

//字符安全过滤
function safe_replace($string) {
    if(is_array($string)){
        $string=implode(',',$string);
        $string=htmlspecialchars(str_shuffle($string));
    } else{
        $string=htmlspecialchars($string);
    }
    $string = str_replace('%20','',$string);
    $string = str_replace('%27','',$string);
    $string = str_replace('%2527','',$string);
    $string = str_replace('*','',$string);
    $string = str_replace('"','"',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','<',$string);
    $string = str_replace('>','>',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
    return $string;
}

/*	**功能:将多维数组合并为一位数组
**$array:需要合并的数组
**$clearRepeated:是否清除并后的数组中得重复值
*/
function array_multiToSingle($array,$clearRepeated=false){
    if(!isset($array)||!is_array($array)||empty($array)){
        return false;
    }
    if(!in_array($clearRepeated,array('true','false',''))){
        return false;
    }
    static $result_array=array();
    foreach($array as $k=>$value){
        if(is_array($value)){
            array_multiToSingle($value);
        }else{
            $result_array[$k]=$value;
        }
    }
    if($clearRepeated){
        $result_array=array_unique($result_array);
    }
    return $result_array;
}

//删除二维数组中重复的值
$array=array(
    array("ID"=>21,"name"=>"kitty"),
    array("ID"=>22,"name"=>"sony"),
    array("ID"=>17,"name"=>"picker"),
    array("ID"=>17,"name"=>"picker"));
function a_array_unique($array)//写的比较好
{
    $out = array();
    foreach ($array as $key=>$value) {
        if (!in_array($value, $out))
        {
            $out[$key] = $value;
        }
    }
    return $out;
}




//二维数组转成一维
 function array_1($result){
    foreach($result as $k=>$v){
        foreach($v as $a=>$b){
            $res[$a]=$b;
        }
    }
    return $res;
}

//j计算本周的开始日期和结束日期
function weeks(){
    $time = time();
//判断当天是星期几,0表星期天,1表星期一,6表星期六
    $w_day=date("w",$time);
    //php处理当前星期时间点上,根据当天是否为星期一区别对待
    if($w_day=='1'){
        $cflag = '+0';
        $lflag = '-1';
    }
    else {
        $cflag = '-1';
        $lflag = '-2';
    }
    //本周一零点的时间戳
    $start_time = strtotime(date('Y-m-d',strtotime("$cflag week Monday", $time)));

    //本周末零点的时间戳
    $stop_time = strtotime(date('Y-m-d',strtotime("$cflag week Monday", $time)))+7*24*3600;

    // php获取本月起始时间戳;
    $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
    //获取本月结束时间戳
    $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
    //获取指定时间的时间戳
    $time = mktime ( 15, 32, 10, date ( 'm' ), date ( 'd' ), date ( 'Y' ) );
}
// 获取唯一订单号
 function getSn(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
/**
 * 去除字符串中的指定字符
 * @param string $str 待处理字符串
 * @param string $chars 需去掉的特殊字符
 * @return string
 */
function sp_strip_chars($str, $chars='?<*.>\'\"'){
    return preg_replace('/['.$chars.']/is', '', $str);
}
/**
 * 格式化字符串
 * @param string $str
 * @return string
 */
function formatStr($str) {
    $arr = array(' ', '	', '&', '@', '#', '%',  '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');
    foreach ($arr as $v) {
        $str = str_replace($v, '', $str);
    }
    return $str;
}


/**
 * 检查用户对某个url,内容的可访问性,用于记录如是否赞过,是否访问过等等;开发者可以自由控制,对于没有必要做的检查可以不做,以减少服务器压力
 * @param number $object 访问对象的id,格式:不带前缀的表名+id;如posts1表示xx_posts表里id为1的记录;如果object为空,表示只检查对某个url访问的合法性
 * @param number $count_limit 访问次数限制,如1,表示只能访问一次
 * @param boolean $ip_limit ip限制,false为不限制,true为限制
 * @param number $expire 距离上次访问的最小时间单位s,0表示不限制,大于0表示最后访问$expire秒后才可以访问
 * @return true 可访问,false不可访问
 */
function sp_check_user_action($object="",$count_limit=1,$ip_limit=false,$expire=0){
    $common_action_log_model=M("CommonActionLog");//实例化记录访问信息的表
    $action=MODULE_NAME."-".CONTROLLER_NAME."-".ACTION_NAME;//记录访问的链接,模块。控制器。方法
    $userid=get_current_userid();//获取当前用户ID

    $ip=get_client_ip();//获取当前的IP

    $where=array("user"=>$userid,"action"=>$action,"object"=>$object);
    if($ip_limit){//是否限制ip
        $where['ip']=$ip;
    }

    $find_log=$common_action_log_model->where($where)->find();//取出一条访问记录

    $time=time();
    if($find_log){//如果记录存在
        $common_action_log_model->where($where)->save(array("count"=>array("exp","count+1"),"last_time"=>$time,"ip"=>$ip));
        if($find_log['count']>=$count_limit){//记录中的次数是否大于规定的次数
            return false;
        }

        if($expire>0 && ($time-$find_log['last_time'])<$expire){//是否符合规定的间隔时间
            return false;
        }
    }else{//如果记录不存在就添加此次记录
        $common_action_log_model->add(array("user"=>$userid,"action"=>$action,"object"=>$object,"count"=>array("exp","count+1"),"last_time"=>$time,"ip"=>$ip));
    }

    return true;
}
/**
 *快速获取url变量
 *@param $string $token,$token2,$token3,$token4...
 *@author 技术支持:张湘南
 *用法:get(token,openid.id);
 **/
function get($token,$token2,$token3,$token4,$token5,$token6,$token7){
    $a=array($token=>$_GET[$token],$token2=>$_GET[$token2],$token3=>$_GET[$token3],$token4=>$_GET[$token4],$token5=>$_GET[$token5],$token6=>$_GET[$token6],$token7=>$_GET[$token7]);
    $a=array_filter($a);
    return $a;
}
/**
 *快速获取post变量
 **/
function post($token,$token2,$token3,$token4,$token5,$token6,$token7){
    $a=array($token=>$_POST[$token],$token2=>$_POST[$token2],$token3=>$_POST[$token3],$token4=>$_POST[$token4],$token5=>$_POST[$token5],$token6=>$_POST[$token6],$token7=>$_POST[$token7]);
    $a=array_filter($a);
    return $a;
}
/**
 *当前时间往后的时间
 *$int 数字
 *$string 时间格式
 *用法:$date=date_date(30,'Y-m-d');
 *@author 技术支持:张湘南
 **/
function date_date($int,$string){
    $a = -86400;//因为for有个$a+=86400; 为了取当前选定时间-86400
    for ($i=0; $i<$int; $i++){
        $a+=86400;
        $aDate[] = date($string,time()+$a);
    }
    return $aDate;
}
/**
 *删除有序数组中相同的元素
 *$array  二维数组
 *$string 子段
 *@author 技术支持:张湘南
 *用法:array_delete($list,'wg');
 **/
$array=array(
    array("ID"=>21,"name"=>"kitty"),
    array("ID"=>22,"name"=>"sony"),
    array("ID"=>17,"name"=>"picker"),
    array("ID"=>18,"name"=>"picker"));
function array_delete($array,$string){
    foreach ($array as $ke => $v){
        $array[$v[$string]][$string]=$v[$string];
        $array[$v[$string]]=$v;
        unset($array[$ke]);//删除原来的
    }
    unset($array['']);//删除键名为空的
    return $array;
}

//替换路径中的反斜杠
function _dir_path($path) {
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1) != '/')
        $path = $path . '/';
    return $path;
}

//高亮内容中的指定关键字
function highlight($content,$key)
{
    //ini_set('memory_limit', '32M');
    set_time_limit(0);
    $con = '';
    $k_fi = substr($key, 0, 1);    //取得关键词第一个字符
    $k_len = strlen($key);   //计算关键词字数
    $l_len = strlen($content);    //计算备查文章字数
    for ($l_n = 0; $l_n < $l_len; $l_n++)  //根据备查文章字数开始循环
    {
        $l_s = substr($content, $l_n, 1);  //取得备查文章当前字符
        if ($l_s == "<") {   //如果这个字符是标签的开始的话
            while ($l_s != ">") { //我们就寻找这个标签的关闭
                $con .= $l_s;  //导入结果
                $l_n++;  //当然要开始取备查文章的下一个字符
                $l_s = substr($content, $l_n, 1);
            }
            $con .= $l_s;
        } elseif ($l_s == $k_fi) { //如果这个字符与关键词第一个字符相同的话
            $l_key = substr($content, $l_n, $k_len);  //取备查文章当前位置是否匹配关键词
            if ($l_key != $key) {
                $con .= $l_s;  //导入结果
            } else { //如果匹配
                $l_n += $k_len - 1;  //计数跳过相应字数
                $con .= "<span style=\"color:hsl(0, 100%, 40%);\">";
                $con .= $key;
                $con .= "</span>";  //加亮关键词
            }
        } else {
            $con .= $l_s;  //导入结果
        }
    }
    return $con;
}
//删除指定目录下的文件:
function deldir($dir)
{
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;

            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
}

//删除数组中的指定元素1
function del_array($arr,$val){
    foreach ($arr as $key=>$value)
    {
        if ($value === $val)
            unset($arr[$key]);
    }
    return $arr;
}


//删除数组中的指定元素2
function del_array2($arr,$var){
    $key = array_search($var, $arr);
    if($key !== false){
        array_splice($arr1, $key, '');
    }
    return $var;

}
$arr2 = array(1,3, 5,7,8);


/**
 * 转化数据库保存的文件路径,为可以访问的url
 * @param string $file
 * @param boolean $withhost
 * @return string
 */
function sp_get_asset_upload_path($file,$withhost=false){
    if(strpos($file,"http")===0){
        return $file;
    }else if(strpos($file,"/")===0){
        return $file;
    }else{
        $filepath=C("TMPL_PARSE_STRING.__UPLOAD__").$file;
        if($withhost){
            if(strpos($filepath,"http")!==0){
                $http = 'http://';
                $http =is_ssl()?'https://':$http;
                $filepath = $http.$_SERVER['HTTP_HOST'].$filepath;
            }
        }
        return $filepath;

    }
}

//通过ip获取地理位置使用的是新浪的接口
function getiploc_sina($queryip){
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryip;
    $ch = curl_init($url);
    curl_setopt($ch,curlopt_encoding ,'utf8');
    curl_setopt($ch, curlopt_timeout, 5);
    curl_setopt($ch, curlopt_returntransfer, true) ; // 获取数据返回
    $location = curl_exec($ch);
    $location = json_decode($location);
    curl_close($ch);
    $loc = "";
    if($location===false) return "";
    if (empty($location->desc)) {
        $loc = $location->province.$location->city.$location->district.$location->isp;
    }else{
        $loc = $location->desc;
    }
    return $loc;
}
//通过百度接口获取客户端地址
function ipdress(){
    //$getIp='163.125.149.128';

    //echo 'IP:',$getIp;
    echo '<br/>';
    $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=7IZ6fgGEGohCrRKUE9Rj4TSQ&ip={$getIp}&coor=bd09ll");
    $json = json_decode($content);
    echo 'log:',$json->{'content'}->{'point'}->{'x'};//按层级关系提取经度数据
    echo '<br/>';
    echo 'lat:',$json->{'content'}->{'point'}->{'y'};//按层级关系提取纬度数据
    echo '<br/>';
    print $json->{'content'}->{'address'};//按层级关系提取address数据
}


/* 判断是电脑还是手机访问*/
function isMobil()
{
    $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $useragent_commentsblock = preg_match('|\(.*?\)|', $useragent, $matches) > 0 ? $matches[0] : '';
    $mobile_os_list = array
    (
        'Google Wireless Transcoder',
        'Windows CE',
        'WindowsCE',
        'Symbian',
        'Android',
        'armv6l',
        'armv5',
        'Mobile',
        'CentOS',
        'mowser',
        'AvantGo',
        'Opera Mobi',
        'J2ME/MIDP',
        'Smartphone',
        'Go.Web',
        'Palm',
        'iPAQ'
    );
    $mobile_token_list = array
    (
        'Profile/MIDP',
        'Configuration/CLDC-',
        '160×160',
        '176×220',
        '240×240',
        '240×320',
        '320×240',
        'UP.Browser',
        'UP.Link',
        'SymbianOS',
        'PalmOS',
        'PocketPC',
        'SonyEricsson',
        'Nokia',
        'BlackBerry',
        'Vodafone','BenQ',
        'Novarra-Vision',
        'Iris',
        'NetFront',
        'HTC_',
        'Xda_',
        'SAMSUNG-SGH',
        'Wapaka',
        'DoCoMo',
        'iPhone',
        'iPod'
    );
    $found_mobile =CheckSubstrs($mobile_os_list, $useragent_commentsblock) ||
        CheckSubstrs($mobile_token_list, $useragent);
    if ($found_mobile)
    {
        $way= '手机登录';//'手机登录'
    }
    else
    {
        $way= '电脑登录';//'电脑登录'
    }
    return $way;
}

//获取客户端的真实Ip
function get_real_ip(){
    $ip=false;
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ips=explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
        if($ip){ array_unshift($ips, $ip); $ip=FALSE; }
        for ($i=0; $i < count($ips); $i++){
            if(!eregi ('^(10│172.16│192.168).', $ips[$i])){
                $ip=$ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
/**
 * 根据配置类型解析配置
 * @param  integer $type  配置类型
 * @param  string  $value 配置值
 */
 function parse($type, $value){
    switch ($type) {
        case 3: //解析数组
            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
            if(strpos($value,':')){
                $value  = array();
                foreach ($array as $val) {
                    list($k, $v) = explode(':', $val);
                    $value[$k]   = $v;
                }
            }else{
                $value =    $array;
            }
            break;
    }
    return $value;
}
$info=array(
    "user"=>array(
        array(1,"zhangsan",20,"nan"),
        array(2,"lisi",20,"nan"),
        array(3,"wangwu",25,"nv")
    ),
    "score"=>array(
        array(1,100,98,95,96),
        array(2,56,98,87,84),
        array(3,68,75,84,79)
    ),
    "connect"=>array(
        array(1,'2468246',"salkh@bbs.com"),
        array(2,'343681643',"aikdki@sina.com"),
        array(3,'3618468',"42816@qq.com")
    )
);
/*
* 把多维数组转化成一维数组或是字符串(去重)
* @param array $arr 要转化的多数组
* @param bool $returnArr 是否返回一维数组,默认为true,false表示返回字符串
* @author fanglor
* @date 2011-11-21
*/
function multi_array_to_one ($arr ,$returnArr = true) {
    static $result = array ();
    if (!is_array ($arr) ) {
        $result[] = $arr;
    } else {
        foreach ($arr as $key => $row ) {
            if (is_array ($row)) {
                multi_array_to_one ($row,$returnArr);
            } else {
                $result[]=$row;
            }
        }
    }
    return $returnArr ? array_unique($result) : implode (',',array_unique($result)) ;
}

/**
 * 遍历目录,结果存入数组。支持php4及以上。php5以后可用scandir()函数代替while循环。
 * @param string $dir
 * @return array
 */
function my_scandir($dir)
{
    $files = array();
    if ( $handle = opendir($dir) ) {
        while ( ($file = readdir($handle)) !== false )
        {
            if ( $file != ".." && $file != "." )
            {
                if ( is_dir($dir . "/" . $file) )
                {
                    $files[$file] = my_scandir($dir . "/" . $file);
                }
                else
                {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
}

 function find_createtime($day,$cid){
//查询当天数据
    if($day==1){
        $today=strtotime(date('Y-m-d 00:00:00'));
        $data['cid']=$cid;
        $data['createtime'] = array('egt',$today);
        return $data;
//查询本周数据
    }else if($day==2){
        $arr=array();
        $arr=getdate();
        $num=$arr['wday'];
        $start=time()-($num-1)*24*60*60;
        $end=time()+(7-$num)*24*60*60;
        $data['cid']=$cid;
        $data['createtime'] = array('between',array($start,$end));
        return $data;
//查询本月数据
    }else if($day==3){
        $start=strtotime(date('Y-m-01 00:00:00'));
        $end = strtotime(date('Y-m-d H:i:s'));
        $data['cid']=$cid;
        $data['createtime'] = array('between',array($start,$end));
        return $data;
//查询本季度数据
    }else if($day==4){
        $month=date('m');
        if($month==1 || $month==2 ||$month==3){
            $start=strtotime(date('Y-01-01 00:00:00'));
            $end=strtotime(date("Y-03-31 23:59:59"));
        }elseif($month==4 || $month==5 ||$month==6){
            $start=strtotime(date('Y-04-01 00:00:00'));
            $end=strtotime(date("Y-06-30 23:59:59"));
        }elseif($month==7 || $month==8 ||$month==9){
            $start=strtotime(date('Y-07-01 00:00:00'));
            $end=strtotime(date("Y-09-30 23:59:59"));
        }else{
            $start=strtotime(date('Y-10-01 00:00:00'));
            $end=strtotime(date("Y-12-31 23:59:59"));
        }
        $data['cid']=$cid;
        $data['createtime'] = array('between',array($start,$end));
        return $data;
//查询本年度数据
    }else if($day==5){
        $year=strtotime(date('Y-01-01 00:00:00'));
        $data['cid']=$cid;
        $data['createtime'] = array('egt',$year);
        return $data;
//全部数据
    }else{
        $data['cid']=$cid;
        return $data;
    }
}
/**
 * 使用正则验证数据
 * @access public
 * @param string $value  要验证的数据
 * @param string $rule 验证规则
 * @return boolean
 */
function regex($value,$rule) {
    $validate = array(
        'require'   =>  '/\S+/', //不为空
        'email'     =>  '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',//邮箱
        'url'       =>  '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'currency'  =>  '/^\d+(\.\d+)?$/',//货币
        'number'    =>  '/^\d+$/',//数字
        'zip'       =>  '/^\d{6}$/', //邮编
        'integer'   =>  '/^[-\+]?\d+$/',//整数
        'double'    =>  '/^[-\+]?\d+(\.\d+)?$/',
        'english'   =>  '/^[A-Za-z]+$/',    //字母
        'mobile'    =>'/^1[3|4|5|8][0-9]\d{4,8}$/',//手机
        'hybrid'    =>"/^[a-zA-Z0-9]{4,16}$/", //验证字符串是否只含数字与英文,字符串长度并在4~16个字符之间
        'phone'     =>'/^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$/',     //电话号码
        'card'      =>'/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/'
    );
    // 检查是否有内置的正则表达式
    if(isset($validate[strtolower($rule)]))
        $rule       =   $validate[strtolower($rule)];
    return preg_match($rule,$value)===1;
}


function message($msgTitle,$message,$jumpUrl){
    $str = '<!DOCTYPE HTML>';
    $str .= '<html>';
    $str .= '<head>';
    $str .= '<meta charset="utf-8">';
    $str .= '<title>页面提示</title>';
    $str .= '<style type="text/css">';
    $str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';
    $str .= '</style>';
    $str .= '</head>';
    $str .= '<body>';
    $str .= '<div class="message">';
    $str .= '<h3>'.$msgTitle.'</h3>';
    $str .= '<div class="msg_txt">';
    $str .= '<h4 class="red">'.$message.'</h4>';
    $str .= '<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>';
    $str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";
    $str .= '</div>';
    $str .= '</div>';
    $str .= '</body>';
    $str .= '</html>';
    echo $str;
}


$str='420982198906027890';
echo regex($str,'card');

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值