<?php//方法库
if (!function_exists('mobile_regular_expression')) { /** * 国际手机号码正则验证规则获取 * @param string $phone_code 国际区号 * @return string */ function mobile_regular_expression($phone_code) { $list = [ '-1' => ['regu' => '/^\d{3,15}$/', 'name' => '不验证区号正则'], '-2' => ['regu' => '', 'name' => '验证区号正则'],
'+86' => ['regu' => '/^1[3-9]\d{9}$/', 'name' => '中国大陆'], '+852' => ['regu' => '/^(5[1234569]\d{6}|6\d{7}|9[0-8]\d{6})$/', 'name' => '中国香港'], '+853' => ['regu' => '/^6\d{7}$/', 'name' => '中国澳门'], '+886' => ['regu' => '/^0?9\d{8}$/', 'name' => '中国台湾'], '+1' => ['regu' => '/^\d{10,12}$/', 'name' => '美国'], '+82' => ['regu' => '/^0?[71](?:\d{8,9})$/', 'name' => '韩国'], '+81' => ['regu' => '/^0?[789](?:\d{8}|\d{9})$/', 'name' => '日本'], '+65' => ['regu' => '/^[89]\d{7}$/', 'name' => '新加坡'], '+60' => ['regu' => '/^1\d{8,9}$/', 'name' => '马来西亚'], '+61' => ['regu' => '/^4\d{8,9}$/', 'name' => '澳大利亚'], '+63' => ['regu' => '/^\d{10}$/', 'name' => '菲律宾'], '+62' => ['regu' => '/^0?[2-9]{1}\d+$/', 'name' => '印度尼西亚'], ]; $phone_code = empty($phone_code) ? '+86' : $phone_code; return empty($list[$phone_code]) ? '' : $list[$phone_code]['regu']; }}
if(!function_exists('str_length')){ /** * @param Request $request * @return 获取字符串长度 */ function str_length($str, $charset = 'utf-8') { if ($charset == 'utf-8') $str = iconv('utf-8', 'gb2312', $str); $num = strlen($str); $cnNum = 0; for ($i = 0; $i < $num; $i++) { if (ord(substr($str, $i + 1, 1)) > 127) { $cnNum++; $i++; } } $enNum = $num - ($cnNum * 2); $number = ($enNum / 2) + $cnNum; return ceil($number); }}
if(!function_exists('cc_msubstr')){ /** * @param Request $request * @return mixed截取字符串 */ function cc_msubstr($str, $length, $start = 0, $charset = "utf-8", $suffix = true) { if (function_exists("mb_substr")) { return mb_substr($str, $start, $length, $charset); } elseif (function_exists('iconv_substr')) { return iconv_substr($str, $start, $length, $charset); } $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)); if ($suffix) { return $slice . ".."; } else { return $slice; } }}
if(!function_exists('word_time')){ /** * 时间转时间段 */ function word_time($time) { $time = (int)substr($time, 0, 10); $int = time() - $time; $str = ''; if ($int <= 2) { $str = sprintf('刚刚', $int); } elseif ($int < 60) { $str = sprintf('%d秒前', $int); } elseif ($int < 3600) { $str = sprintf('%d分钟前', floor($int / 60)); } elseif ($int < 86400) { $str = sprintf('%d小时前', floor($int / 3600)); } elseif ($int < 2592000) { $str = sprintf('%d天前', floor($int / 86400)); } else { $str = date('Y-m-d H:i:s', $time); } return $str; }}
if(!function_exists('http_request')){ /** * @function curl 请求 * * @param $url 请求url * @param null $data 请求参数 * @param int $secound 设置超时时间 0 表示无限 * @param null $header 设置请求头部参数 * @return mixed */ function http_request($url, $data = null, $secound = 0, $header = NULL) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if ($secound > 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $secound); //设置超时时间 } if (!empty($header)) { curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //设置头信息的地方 } if (!empty($data)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; }}
if(!function_exists('filter_str')) { /** * 过滤特殊字符(微信qq) * * @param unknown $str */ function filter_str($str) { if ($str) { $name = $str; $name = preg_replace_callback('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', function ($matches) { return ''; }, $name); $name = preg_replace_callback('/xE0[x80-x9F][x80-xBF]‘.‘|xED[xA0-xBF][x80-xBF]/S', function ($matches) { return ''; }, $name); // 汉字不编码 $name = json_encode($name); $name = preg_replace_callback("/\\\ud[0-9a-f]{3}/i", function ($matches) { return ''; }, $name); if (!empty($name)) { $name = json_decode($name); return $name; } else { return ''; } } else { return ''; } }}
if(!function_exists('get_city_by_ip')) { /** * 根据 ip 获取 当前城市 */ function get_city_by_ip() { if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $cip = $_SERVER["HTTP_CLIENT_IP"]; } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } elseif (!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ""; } $url = 'https://restapi.amap.com/v3/ip'; $data = array( 'output' => 'json', 'key' => '7b9bf1c7628252f14c79c8e4c07c0ac5', 'ip' => $cip );
$postdata = http_build_query($data); $opts = array( 'http' => array( 'method' => 'GET', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) );
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
if (!empty($result)) { $res = json_decode($result, true);
if (!empty($res)) {
if (empty($res['province'])) { $res['province'] = '北京市'; } if (!empty($res['province']) && $res['province'] == "局域网") { $res['province'] = '北京市'; }
if (is_array($res['province'])) { $province_count = count($res['province']); if ($province_count == 0) { $res['province'] = '北京市'; } } if (is_array($res['city'])) { $city_count = count($res['city']); if ($city_count == 0) { $res['city'] = '北京市'; } } } else { $res['province'] = '北京市'; $res['city'] = '北京市'; }
return $res; } else { return array( "province" => '北京市', "city" => '北京市' ); } }}
if(!function_exists('is_url')) { /** * 是否是url链接 * @param unknown $string * @return boolean */ function is_url($string) { if (strstr($string, 'http://') === false && strstr($string, 'https://') === false) { return false; } else { return true; } }}
if(!function_exists('download')) {//$fpath为下载文件所在文件夹,默认是downlod function download($fname, $newname = '') { if (empty($newname)) { $newname = $fname; } else { $ext = substr($fname, strrpos($fname, '.') + 1); $newname = $newname . "." . $ext; }
//检查文件是否存在 if (!file_exists($fname)) { header('HTTP/1.1 404 NOT FOUND'); } else { //以只读和二进制模式打开文件 $file = fopen($fname, "rb");
//告诉浏览器这是一个文件流格式的文件 Header("Content-type: application/octet-stream"); //请求范围的度量单位 Header("Accept-Ranges: bytes"); //Content-Length是指定包含于请求或响应中数据的字节长度 Header("Accept-Length: " . filesize($fname)); //用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。 Header("Content-Disposition: attachment; filename=" . $newname);
//读取文件内容并直接输出到浏览器 echo fread($file, filesize($fname)); fclose($file); exit (); } }}
if(!function_exists('encrypt')) { /** * 系统加密方法 * * @param string $data * 要加密的字符串 * @param string $key * 加密密钥 * @param int $expire * 过期时间 单位 秒 * @return string */ function encrypt($data, $key = '', $expire = 0) { $key = md5(empty ($key) ? 'niucloud' : $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)); }}
if(!function_exists('decrypt')) { /** * 系统解密方法 * * @param string $data * 要解密的字符串 (必须是encrypt方法加密的字符串) * @param string $key * 加密密钥 * @return string */ function decrypt($data, $key = '') { $key = md5(empty ($key) ? 'niucloud' : $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); }}if(!function_exists('get_sign')) { /** * md5签名 * @param unknown $key * @param unknown $params * @return string */ function get_sign($key, $params) { if (!is_array($params)) $params = array();
ksort($params); $text = ''; foreach ($params as $k => $v) { $text .= $k . $v; } return md5($key . $text . $key);
}}
if(!function_exists('check_phone')) { /** * 验证手机 * */ function check_phone($value) { if (preg_match('/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/', $value)) { return true; } else { return false; } }}
if(!function_exists('check_email')) {
/** * 验证邮箱 * */ function check_email($mail) { $checkmail = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/"; if (preg_match_all($checkmail, $mail)) { return true; } else { return false; } }}
if(!function_exists('get_ip')) { /** * 获取客户端真实ip * @return array|false|string */ function get_ip() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return $ip; }}
if(!function_exists('copydirs')) {
/** * 复制文件夹 * @param string $source 源文件夹 * @param string $dest 目标文件夹 */ function copydirs($source, $dest) { if (!is_dir($dest)) { mkdir($dest, 0755, true); } foreach ( $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item ) { if ($item->isDir()) { $sontDir = $dest . DS . $iterator->getSubPathName(); if (!is_dir($sontDir)) { mkdir($sontDir, 0755, true); } } else { copy($item, $dest . DS . $iterator->getSubPathName()); } } }}
if(!function_exists('rmdirs')) {
/** * 删除文件夹 * @param string $dirname 目录 * @param bool $withself 是否删除自身 * @return boolean */ function rmdirs($dirname, $withself = true) { if (!is_dir($dirname)) return false; $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST );
foreach ($files as $fileinfo) { $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $todo($fileinfo->getRealPath()); } if ($withself) { @rmdir($dirname); } return true; }}
if(!function_exists('datetime')) {
/** * 将时间戳转换为日期时间 * @param int $time 时间戳 * @param string $format 日期时间格式 * @return string */ function datetime($time, $format = 'Y-m-d H:i:s') { $time = is_numeric($time) ? $time : strtotime($time); return date($format, $time); }}
if(!function_exists('get_random_string')) {
/** * 随机生成数字字母组合 * */ function get_random_string($len, $chars = null) { if (is_null($chars)) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; } //mt_srand(10000000*(double)microtime()); mt_srand(time()); for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) { $str .= $chars[mt_rand(0, $lc)]; } return $str; }}
if(!function_exists('is_weixin')) {
/** * 判断当前是否是微信浏览器 */ function is_weixin() { if (strpos($_SERVER['HTTP_USER_AGENT'],
'MicroMessenger') !== false) {
return 1; }
return 0; }}
if(!function_exists('is_ali')) {
/** * 判断当前是否是支付宝浏览器 */ function is_ali() { if (strpos($_SERVER['HTTP_USER_AGENT'],
'Alipay') !== false) {
return 1; }
return 0; }}
if(!function_exists('rand_str')) {
/** * 随机产生六位数密码 */ function rand_str($len = 6, $format = 'ALL') { switch ($format) { case 'ALL': $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break; case 'CHAR': $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break; case 'NUMBER': $chars = '0123456789'; break; default : $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break; } mt_srand(intval((double)microtime() * 1000000 * getmypid())); $password = ""; while (strlen($password) < $len) $password .= substr($chars, (mt_rand() % strlen($chars)), 1); return $password; }}
if(!function_exists('sign_create')) {
/** * 生成签名、验证签名 * @param $param 接收到的所有参数 * @param $private_key * @return string */ function sign_create($param, $private_key) { //获取到传来的参数数组并排序ksort() ksort($param); $param_string = ''; foreach ($param as $key => $value) { $param_string .= $key . $value; } //md5加密字符串并生成签名 $encrypted = ""; $md5_param_string = md5($param_string); openssl_sign($md5_param_string, $encrypted, $private_key, OPENSSL_ALGO_SHA1); $encrypted = base64_encode($encrypted); return $encrypted; }}
if(!function_exists('verify_sign')) {
/** * 验证签名 */ function verify_sign($param, $sign, $public_key) { //获取到传来的参数数组并排序ksort() ksort($param); $param_string = ''; foreach ($param as $key => $value) { $param_string .= $key . $value; } //md5加密字符串并生成签名 $md5_param_string = md5($param_string); $sign = base64_decode($sign); openssl_pkey_get_public($public_key); $result = openssl_verify($md5_param_string, $sign, $public_key, OPENSSL_ALGO_SHA1) === 1; return $result; }}
// 数字金额转中文if (!function_exists('to_chinese_number')) { function to_chinese_number($num) { $c1 = "零壹贰叁肆伍陆柒捌玖"; $c2 = "分角元拾佰仟万拾佰仟亿"; $num = round($num, 2); //输入金额四舍五入 $num = $num * 100; if (strlen($num) > 10) { return "金额太大,请检查"; } $i = 0; $c = ""; while (1) { if ($i == 0) { $n = substr($num, strlen($num)-1, 1); } else { $n = $num % 10; } $p1 = substr($c1, 3 * $n, 3); $p2 = substr($c2, 3 * $i, 3); if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) { $c = $p1 . $p2 . $c; } else { $c = $p1 . $c; } $i = $i + 1; $num = $num / 10; $num = (int)$num; if ($num == 0) { break; } } $j = 0; $slen = strlen($c); while ($j < $slen) { $m = substr($c, $j, 6); if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') { $left = substr($c, 0, $j); $right = substr($c, $j + 3); $c = $left . $right; $j = $j-3; $slen = $slen-3; } $j = $j + 3; } if (substr($c, strlen($c)-3, 3) == '零') { $c = substr($c, 0, strlen($c)-3); } if (empty($c)) { return "零元整"; }else{ return $c . "整"; } }}
//经纬度转换 高德(腾讯)转 百度if (!function_exists('gd_trans_bd')) { function gd_trans_bd($gd_lat, $gd_lon){ $x_pi = 3.14159265358979324 * 3000.0 / 180.0; $x = $gd_lon; $y = $gd_lat; $z = sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi); $theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi); $bd_lon = $z * cos($theta) + 0.0065; $bd_lat = $z * sin($theta) + 0.006; return [ 'lat' => $bd_lat, 'lng' => $bd_lon ]; }}
// 经纬度转换 百度 转 高德(腾讯)if (!function_exists('bd_trans_gd')) { function bd_trans_gd($bd_lat, $bd_lon){ $x_pi = 3.14159265358979324 * 3000.0 / 180.0; $x = $bd_lon - 0.0065; $y = $bd_lat - 0.006; $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi); $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi); $gg_lon = $z * cos($theta); $gg_lat = $z * sin($theta); return [ 'lat' => $gg_lat, 'lng' => $gg_lon ]; }}
// PHP弹出手机端弹窗if (!function_exists('layer_open')) { function layer_open($msg, $time = 2, $url = ''){ $str = '<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">'; $str .= '<meta name="app-mobile-web-app-capable" content="yes">'; $str .= '<script type="text/javascript" src="/static/js/jquery-1.11.1.min.js"></script>'; $str .= '<script type="text/javascript" src="/static/js/layer/mobile/layer.js"></script>'; $str .= '<script>'; if($url == ''){ $url = "javascript:history.go(-1);"; } $str .= '$(function(){ layer.open({style: "border:none; background-color:rgba(1,1,1,0.4); color:#fff;",content:"' . $msg . '",skin: "msg", time: '.$time.',end:function(){ location.href = "'.$url .'"; } }); });'; $str .= '</script>'; echo $str; exit; }}
// 去除字符串中的emoji表情if (!function_exists('remove_emoji')) { function remove_emoji($text) { $clean_text = "";
// Match Emoticons $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u'; $clean_text = preg_replace($regexEmoticons, '', $text);
// Match Miscellaneous Symbols and Pictographs $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u'; $clean_text = preg_replace($regexSymbols, '', $clean_text);
// Match Transport And Map Symbols $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u'; $clean_text = preg_replace($regexTransport, '', $clean_text);
// Match Miscellaneous Symbols $regexMisc = '/[\x{2600}-\x{26FF}]/u'; $clean_text = preg_replace($regexMisc, '', $clean_text);
// Match Dingbats $regexDingbats = '/[\x{2700}-\x{27BF}]/u'; $clean_text = preg_replace($regexDingbats, '', $clean_text);
return $clean_text; }}
// 二维数组排序(默认正序)if (!function_exists('array_sorts')) { /** * @param $array * @param $field * @param string $sort * @return mixed */ function array_sorts($array, $field, $sort = 'SORT_ASC') { $arrSort = []; foreach ($array as $uniqid => $row) { foreach ($row as $key => $value) { $arrSort[$key][$uniqid] = $value; } } array_multisort($arrSort[$field], constant($sort), $array); return $array; }}
if (!function_exists('get_distance')) { /** * 求两个已知经纬度之间的距离,单位为米 * @param float $lng1 经度 * @param float $lat1 纬度 * @param float $lng2 经度 * @param float $lat2 纬度 * @return float 距离,单位米 */ function get_distance($lng1, $lat1, $lng2, $lat2) { // 将角度转为狐度 $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度 $radLat2 = deg2rad($lat2); $radLng1 = deg2rad($lng1); $radLng2 = deg2rad($lng2); $a = $radLat1 - $radLat2; $b = $radLng1 - $radLng2; $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000; return $s; }}
if (!function_exists('is_json')) { /** * 判断是否为json数据. * @param mixed $data 带判断的数据 * @return int */ function is_json($data) { if (!is_string($data) || $data === null || $data === '' || is_numeric($data)) { return 0; } $data = selfHtmlspecialchars($data, 1); json_decode($data, true); switch (json_last_error()) { case JSON_ERROR_NONE: $is_json = 1; break; default: $is_json = 0; } return $is_json; }}
if (!function_exists('json_format')) { /** * 数据解析 * @param string|mixed $data 待解析数据 * @param int $is_err_return 解析失败,是否原样返回 * @return array|mixed */ function json_format($data, $is_err_return = 0) { if (is_json($data)) { $data = json_decode(selfHtmlspecialchars($data, 1), true); if (!is_array($data)) { // 解决 '"{\"a\":\"b\"}"' 这种数据问题(is_json通过,但需要 decode 多次的问题) $data = []; } } else { $data = $is_err_return ? $data : []; } return $data; //return is_json($data) ? json_decode(selfHtmlspecialchars($data, 1), true) : ($is_err_return ? $data : []); }}
if (!function_exists('selfHtmlspecialchars')) { /** * 自定义字符串实体互转 * @param string $str * @param int $is_decode 0=转为html实体,1=转换普通字符串 * @param int $flags 自定义的转换方式,默认为 单双引号都转换 * @return string */ function selfHtmlspecialchars(string $str, int $is_decode = 0, $flags = ENT_QUOTES): string { return $is_decode ? htmlspecialchars_decode($str, $flags) : htmlspecialchars($str, $flags); }}
if (!function_exists('is_amount')) { /** * 金额校验函数 * @param $value * @param bool $isZero * @param bool $negative * @return bool */ function is_amount($value, $isZero=false, $negative=false){ // 必须是整数或浮点数,且允许为负 if (!preg_match("/^[-]?\d+(.\d{1,2})?$/", $value)){ return false; } // 不为 0 if (!$isZero && empty((int)($value*100))){ return false; } // 不为负数 if (!$negative && (int)($value * 100) < 0){ return false; } return true; }}
if (!function_exists('con_url')) { /** * 富文本中图片路径处理 * @param string $con 处理的字符串 * @param integer $cut_host 是否去掉域名信息(只取出图片的),1=去掉 * @return string */ function con_url($con, $cut_host = 0): string { if (!empty($con)) { $con = stripslashes(selfHtmlspecialchars($con, 1)); $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/"; preg_match_all($pregRule, $con, $imgs); $imgs = $imgs[1]; if (!empty($imgs)) { $new_imgs = []; foreach ($imgs as $key => $value) { $imgs[$key] = '"' . $value . '"'; $new_imgs[] = '"' . ($cut_host ? str_replace(host_url(), '', $value) : path_format($value)) . '"'; } $con = str_replace($imgs, $new_imgs, $con); } } else { $con = ''; // 解决text字段null值的问题 } return $con; }}
if (!function_exists('is_mobile')) { /** * 判断是否手机号. * @param string mobile 需要检验的手机号 * @return bool */ function is_mobile(string $mobile): bool { if (!preg_match('/^1[3-9]\\d{9}$/', $mobile)) { return false; } return true; }}
if (!function_exists('is_email')) { /** * 验证是否为邮箱 * @param $email * @return int */ function is_email($email) { return preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/", $email); }}
if (!function_exists('mobile_hide')) { /** * 手机号中间部分隐藏. * @param $mobile * @return string */ function mobile_hide(string $mobile): string { return empty($mobile) ? '' : substr_replace($mobile, '****', 3 + (strpos($mobile, '+') === false ? 0 : 3), 4); }}
if (!function_exists('is_phone')) { /** * 判断是否电话号(包含固话和手机号) * @param string $phone 需要检验的电话号 * @return bool */ function is_phone(string $phone): bool { if (!preg_match("/^0\d{2,3}-\d{7,8}$|^1[3-9]\d{9}$/", $phone)) { return false; } return true; }}
if (!function_exists('str_replace_explode')){ /** * 替换用户填写的数据为 后台好处理为数组的数据 */ function str_replace_explode( $string ) { $string = str_replace(' ', ',', $string); $string = str_replace(' ', ',', $string); $string = str_replace(',', ',', $string); $string = str_replace(';', ',', $string); $string = str_replace(';', ',', $string);
$l_string = substr($string,0, 1); $r_string = mb_substr($string,-1, 1); if ( $l_string == ',' ) { $string = ltrim($string,','); }
if ( $r_string == ',' ) { $string = rtrim($string, ','); }
return $string; }}
if (!function_exists('pre_month_day')) {/** * 获取上个月的某个时间 */function pre_month_day($time){ $preMonth = mktime(0, 0, 0, date("n", $time), 0, date("Y", $time)); //上个月最后一天的时间戳
$preMonthMaxDay = date("t", $preMonth); //上个月的最大天数
//如果当前月的最大天数大于上个月的最大天数,则以上个月的最大天数为准 比如3月31的上个月今天就是2月28或29 if ($preMonthMaxDay < date("j", $time)) { return date("Y-m-d", $preMonth); }
return date(date("Y-m", $preMonth) . "-d", $time); }}
if (!function_exists('replace_img_alt_title')) { /** * 替换img标签中的 alt 和 title 的值 */ function replace_img_alt_title($content, $title) { $pattern= "/<img.*?src=[\"|\'](.*?)[\"|\'].*?>/"; $replace = '<img src="$1" alt="'.$title.'"title="'.$title.'">'; $html = preg_replace($pattern, $replace, $content); return $html; }}
if (!function_exists('getfiles')) { /** * 递归获取所有文件 * * @param string $path 文件路径 * @param string $allowFiles 匹配文件名的正则表达式 (默认为空 全部文件) * @param number $depth 递归深度, 默认 1 * @return array 所有文件 **/ function getfiles($path, $allowFiles = '', $depth = 1, $substart = 0, &$files = array()){ $depth--; $path = realpath($path) . '/'; $substart = $substart ? $substart : strlen($path);
if (!is_dir($path)){ return false; }
if($handle = opendir($path)){ while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { $path2 = $path . $file; if (is_dir($path2) && $depth > 0){ getfiles($path2, $allowFiles, $depth, $substart, $files); } elseif (empty($allowFiles) || preg_match($allowFiles, $file)) { $files[] = substr($path2, $substart); } } } } sort($files); return $files; }}
if (!function_exists('str_replace_nth')) { // 替换字符串中的第n个字符 function str_replace_nth($search, $replace, $subject, $nth) { $found = preg_match_all('/' . preg_quote($search).'/', $subject, $matches, PREG_OFFSET_CAPTURE); if (false !== $found && $found > $nth) { return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search)); } return $subject; }}
if (!function_exists('getArrayMerge')) { /* * 合并数据,如果键值相等其值相加 * @param array $descs * @param array $json_wares */function getArrayMerge($descs, $json_wares){ if (is_array($descs) && is_array($json_wares)) { $arrayMerge = array(); foreach ($json_wares as $key=>$value) { if (array_key_exists($key, $descs)) { $arrayMerge[$key] = $value + $descs[$key]; unset($descs[$key]); } else { $arrayMerge[$key] = $value; } } return $arrayMerge+$descs; } else { return false; } }}
/* base64格式编码转换为图片并保存对应文件夹 */function base64_image_content($base64_image_content,$path){ //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',time())."/"; if(!file_exists($new_file)){ //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return '/'.$new_file; }else{ return false; } }else{ return false; }}
function getImageByContent($content){ $preMatch = "/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/"; @preg_match_all($preMatch, $content, $img_array); $img_array = isset($img_array[1]) ? array_unique($img_array[1]) : []; return $img_array;}
function esub($str, $length = 0) { if($length < 1){ return $str; } //计算字符串长度 $strlen = (strlen($str) + mb_strlen($str,"UTF-8")) / 2; if($strlen < $length) { return $str; } if(mb_check_encoding($str,"UTF-8")){ $str = mb_strcut(mb_convert_encoding($str, "GBK","UTF-8"), 0, $length, "GBK"); $str = mb_convert_encoding($str, "UTF-8", "GBK"); }else{ return mb_substr($str, 0, 1000); } // $str = rtrim($str," ,.。,-——(【、;‘“??《<@"); return $str;}
if (function_exists("verifySign")) { /* * 生成签名 * @param array $array * @param string $signParam * @param string $signKey * @param bool $isSign * @return bool|string * */ function verifySign($array=array(),$signParam='',$signKey='',$isSign=false){ if(!$array || !$signParam){ return false; } if(!$isSign){ $key = $array[$signParam]; } unset($array[$signParam]); ksort($array); $str=""; foreach ($array as $k=>$v) { $v = urlencode(htmlspecialchars_decode($v)); $str .= "&{$k}={$v}"; } $str = substr($str, 1); return $isSign ? $str."&{$signParam}=".md5($str.$signKey) : $key == md5($str.$signKey); }}


发表评论 取消回复