php 常用函数库(var_export 现代紧凑风格、毫秒时间戳、高效遍历目录、语义化时间、计算间隔天数、计算生日年龄、不重复的序列号)

php 常用函数库(var_export 现代紧凑风格、毫秒时间戳、高效遍历目录、语义化时间、计算间隔天数、计算生日年龄、不重复的序列号)

var_export() 方法的现代风格版

/**
 * var_export() 方法的现代风格版
 * 说明:原始版:array(), 现代版:[]
 * @param mixed $var
 * @param string $indent 缩进内容,默认是空格
 * @param boolean $isCompact 是否紧凑模式,即数组是否换行
 * @return string
 */
function varExport($var, $indent = '', $isCompact = true)
{
    switch (gettype($var)) {
        case "string":
            return '\'' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '\'';
        case "array":
            if (count($var) == 0) {
                return '[]';
            }
            $newLine = $isCompact ? '' : "\n";
            $itemSpace = $isCompact ? "$indent " : "$indent    ";
            $indexed = array_keys($var) === range(0, count($var) - 1);
            $r = [];
            foreach ($var as $key => $value) {
                $r[] = $itemSpace . ($indexed ? "" : varExport($key) . " => ") . varExport($value, $itemSpace);
            }
            return "[$newLine" . implode(",$newLine", $r) . "$newLine" . $indent . "]";
        case "boolean":
            return $var ? "TRUE" : "FALSE";
        default:
            return var_export($var, true);
    }
}

高效递归遍历文件夹

/**
 * PHP 高效遍历文件夹(大量文件不会卡死,带文件名排序功能)
 * @param string $path 目录路径
 * @param integer $level 目录深度层级
 * @param boolean $showfile 是否显示文件(否则只遍历显示目录)
 * @param array $skips 要忽略的文件路径集合
 * @param integer $deepth 扫描深度
 */
function fastScanDir($path = './', $level = 0, $showfile = true, $skips = array(), $deepth = 0)
{
    if (!file_exists($path) || ($deepth && $level > $deepth)) {
        return array();
    }
    $path = str_replace('//', '/', $path . '/');
    $file = new \FilesystemIterator($path);
    $filename = '';
    $icon = ''; // 树形层级图形
    if ($level > 0) {
        $icon = ('|' . str_repeat('--', $level));
    }
    $outarr = array();
    foreach ($file as $fileinfo) {
        $filename = iconv('GBK', 'utf-8', $fileinfo->getFilename()); // 解决中文乱码
        $filepath = $path . $filename;
        if ($fileinfo->isDir()) {
            if (!($skips && in_array($filepath . '/', $skips))) {
                $outarr[$filename] = array('path' => $filepath, 'type' => 'dir', 'icon' => $icon);
                $outarr[$filename]['children'] = fastScanDir($filepath, $level + 1, $showfile);
            }
            continue;
        }
        if ($showfile && !($skips && !in_array($filepath, $skips))) {
            $outarr[$filename] = array('path' => $filepath, 'type' => 'file', 'icon' => $icon);
        }
    }
    if ($outarr) {
        ksort($outarr);
    }
    return $outarr;
}

返回标准格式消息

/**
 * 返回标准消息格式
 * @param integer|boolean $status 状态,值为 0 或 1
 * @param string $msg 错误消息内容
 * @param mixed $data 成功的数据
 * @param string $code 代码
 * @return array ['status','msg','data','code']
 */
function stdmessage($status, $msg, $data = '', $code = '')
{
    return [
        'status' => intval($status),
        'msg'  => $msg,
        'data' => $data,
        'code' => $code,
    ];
}

返回语义化时间格式

/**
 * 返回语义化时间
 * @param integer|string $time 时间
 * @param string $break 断点,超过断点以后的时间会直接以指定的日期格式显示
 * @param string $format 日期格式, 与$break参数结合使用
 * @param boolean $aliasable 是否允许以 昨天、前天 来代替 1 天前、2 天前
 * @return string 返回语义化时间,例如:几秒,几分,几小时,几天前,几小时前,几月前 等
 * @example 
 *      humantime(strtotime('-5 month'), 'month') 返回 2019-10-27 17:50:17
 *      humantime(strtotime('-5 month'), 'year') 返回 5 个月前
 *      humantime(strtotime('yesterday')) 返回 昨天
 *      humantime(strtotime('-2 day')); 返回 前天
 */
function humantime($time, $break = '', $format = 'Y-m-d H:i:s', $aliasable = true)
{
    if (!$time) {
        return '';
    }
    if (!is_numeric($time)) {
        $time = strtotime($time);
    }
    $text = '';
    $seconds = time() - $time;
    if ($seconds > 0) {
        $formater = array(
            'second' => ['time' => '1', 'text' => '秒'],
            'minute' => ['time' => '60', 'text' => '分钟'],
            'hour' => ['time' => '3600', 'text' => '小时'],
            'day' => ['time' => '86400', 'text' => '天', 'alias' => ['1' => '昨天', '2' => '前天']],
            'week' => ['time' => '604800', 'text' => '星期'],
            'month' => ['time' => '2592000', 'text' => '个月'],
            'year' => ['time' => '31536000', 'text' => '年'],
        );
        $prevName = '';
        foreach ($formater as $name => $data) {
            if ($seconds < intval($data['time'])) {
                $prevData = $formater[$prevName];
                $count = floor($seconds / intval($prevData['time']));
                if ($aliasable && isset($prevData['alias']) && isset($prevData['alias'][strval($count)])) {
                    $text = $prevData['alias'][strval($count)];
                    break;
                }
                $text = $count . ' ' . $prevData['text'] . '前';
                break;
            }
            $prevName = $name;
            if ($break && ($name == $break)) {
                $text = date($format, $time);
                break;
            }
        }
    } else {
        $text = date($format, $time);
    }
    return $text;
}

返回当前时间的毫秒时间戳

/**
 * 返回当前的毫秒时间戳
 */
function microtimestamp()
{
    return round(microtime(true) * 1000);
}

计算两个日期的相差天数

/**
 * 计算两个日期的相差天数
 * @param string $date1 日期1
 * @param string $date1 日期2
 * @return int 返回相差的天数
 */
function diffDays($date1, $date2)
{
    return abs(strtotime($date1) - strtotime($date2)) / 86400;
}

根据生日计算年龄

/**
 * 根据生日计算年龄
 * @param string $birthday 生日
 * @return int 返回年龄
 */
function calcAge($birthday)
{
    $age = empty($birthday) ? false : strtotime($birthday);
    if (!$age) {
        return 0;
    }
    list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
    list($y2, $m2, $d2) = explode("-", date("Y-m-d"), time());
    $age = $y2 - $y1;
    if (intval($m2 . $d2) < intval($m1 . $d1)) {
        $age -= 1;
    }
    return $age;
}

返回简短文字内容

/**
 * 返回简短文字
 * @param string $text
 * @param integer $length 前面保留的长度
 * @param integer $lastLen 后面保留的长度
 * @param string $ellipsis 省略号
 * @return string 返回截短的字符串
 */
function shortText($text, $length, $lastLen = 0, $ellipsis  = '...')
{
    if (empty($text) || mb_strlen($text) <= $length) {
        return $text;
    }
    if ($lastLen > 0) {
        $text = mb_substr($text, 0, $length - $lastLen) . $ellipsis . mb_substr($text, -$lastLen);
    } else {
        $text = mb_substr($text, 0, $length) . $ellipsis;
    }
    return  $text;
}

返回简短MD5内容

/**
 * 返回简短 MD5 (16位)
 * @param string $text
 * @param integer $start 起始位置,默认值 8
 * @param integer $len 长度,默认值 16
 * @return string
 */
function shortMD5($text, $start = 8, $len = 16)
{
    return substr(md5(strval($text)), $start, $len);
}

返回不重复的序列号

/**
 * 返回不重复序列号
 * 用途:唯一订单号、序列号等
 * 说明:新的字符串长度大约是原来长度的一半,比如12位生成6位,21位生成13位
 * @param string $prefix 前缀
 * @return string
 */
function hashSerial($prefix = '')
{
    $time = date('y-m-d-h-i-s');
    if (is_numeric($prefix)) {
        $time = chunk_split(strval($prefix), 2, '-') . $time;
        $prefix = '';
    }
    $atime = explode('-', $time);
    foreach ($atime as $stime) {
        $itime = $stime * 1;
        if ($itime < 26) {
            $prefix .= chr(65 + $itime);
            continue;
        }
        if ($itime >= 48 && $itime <= 57) {
            $prefix .= chr($itime);
            continue;
        }
        $prefix .= $stime;
    }
    return $prefix;
}

去除SQL脚本中的所有注释内容

/**
 * 去除SQL脚本中的所有注释内容
 * @param string $sqltext 多行SQL文本
 * @return string 返回没有注释的SQL文本
 */
function clearSqlComments($sqltext)
{
    $lines = explode("\n", $sqltext);
    $data = [];
    $hasMultip = false;
    foreach ($lines as $line) {
        // 去除空行
        $line = ltrim($line);
        if ($line == '') {
            continue;
        }
        // 去除单行注释
        $line = ltrim(preg_replace("/--[^\n|\r|^']*[\n|\r]$/", '', $line));
        if ($line == '') {
            continue;
        }
        // 去除多行注释
        if (0 === strpos($line, '/*')) {
            $hasMultip = true;
            continue;
        }
        if (0 === strpos($line, '*/')) {
            $hasMultip = false;
            continue;
        }
        if ($hasMultip && 0 == strpos($line, '*')) {
            continue;
        }
        $data[] = $line;
    }
    return implode("\n", $data);
}

分割多行SQL文本到数组

/**
 * 分割多行SQL文本到数组
 * @param string $sqltext 多行SQL文本
 * @return array 返回数组
 */
function splitSqlText($sqltext)
{
    return empty($sqltext) ? [] : explode(";\r", $sqltext);
}
posted on 2021-02-25 09:58  sochishun  阅读(214)  评论(0编辑  收藏  举报