不懂?没有人会嘲笑你;装懂?人人鄙视你;不懂,先研究;再不懂,就问吧!

PHP常用方法汇总

php xjmroots 784℃ 0评论

PHP常用方法汇总

整理一些PHP常用方法、以便不时之需

裁剪字符串、各种编码

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 get_dates() {
       $today              = date('Y-m-d');
       $yesterday          = date('Y-m-d', strtotime('-1 day'));
       $beforeYesterday    = date('Y-m-d', strtotime('-2 day'));
       $day                = date('w') - 1;
       $dates = array(
        'today'             => array('cnName' => '今天', 'date_s' => date('Y-m-d'), 'date_e' => date('Y-m-d')),
        'yesterday'         => array('cnName' => '昨天', 'date_s' => date('Y-m-d', strtotime('-1 day')), 'date_e' => date('Y-m-d', strtotime('-1 day'))),
        'beforeYesterday'   => array('cnName' => '前天', 'date_s' => date('Y-m-d', strtotime('-2 day')), 'date_e' => date('Y-m-d', strtotime('-2 day'))),
        'currentWeek'       => array('cnName' => '本周', 'date_s' => date('Y-m-d', strtotime($today . -$day . ' day')), 'date_e' => date('Y-m-d', strtotime($today . (6 - $day) . ' day'))),
        'lastWeek'          => array('cnName' => '上周', 'date_s' => date('Y-m-d', strtotime($today . (-$day - 7) . ' day')), 'date_e' => date('Y-m-d', strtotime($today . (-1 - $day) . ' day'))),
        'currentMonth'      => array('cnName' => '本月', 'date_s' => date('Y-m-01'), 'date_e' => date('Y-m-t')),
        'lastMonth'         => array('cnName' => '上月', 'date_s' => date('Y-m-01', strtotime(date('Y-m-01') . '-1 day')), 'date_e' => date('Y-m-d', strtotime(date('Y-m-01') . '-1 day'))),
    );
    return $dates;
}

 生成随机字符串

     function createNonceStr($length = 6) {
      //$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $chars = "0123456789";
      $str = "";
      for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
    }

 从URL中取出域名

    function getDomain($url){
        $rs = parse_url($url);
        if(!isset($rs['host'])) return 0;

        $main_url = $rs['host'];
        if(!strcmp(long2ip(sprintf('%u', ip2long($main_url))), $main_url)) {
            return $main_url;
        } else {
            $arr = explode('.', $main_url);
            $count = count($arr);
           $endArr = array('com', 'net', 'org'); //com.cn net.cn 等情况
            if (in_array($arr[$count - 2], $endArr)){
                $domain = $arr[$count - 3] . '.' . $arr[$count - 2] . '.' . $arr[$count - 1];
            } else {
                $domain = $arr[$count - 2] . '.' . $arr[$count - 1];
            }
            return $domain;
        }
    }

 加密解密、来自ONETHINK

//加密
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}
//解密
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $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 base64_decode($str);
}

 数组排序

/**
* 对查询结果集进行排序
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {
   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;
}

 

 

 

 

 

 

 

 

 

 

转载请注明:家明的博客 » PHP常用方法汇总

喜欢 (0)or分享 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址