1、随机数生成函数(来源-微信支付demo案例)
/** * * 产生随机字符串,不长于32位 * @param int $length * @return 产生的随机字符串 */ public static function getNonceStr($length = 32) { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $str =""; for ( $i = 0; $i < $length; $i++ ) { $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1); } return $str; }
2:将对象数组转为普通数组
/** * 将对象数组转为普通数组 * @param $obj * @return array * 此函数支持多维数组处理 */ function objarray_to_array($obj) { $ret = array(); foreach ($obj as $key => $value) { if (gettype($value) == "array" || gettype($value) == "object"){ $ret[$key] = objarray_to_array($value); }else{ $ret[$key] = $value; } } return $ret; }
或者直接使用PHP的强制类型转换: $arr = (array)$obj;
3: 根据ip地址获取地址信息
/** * 根据ip地址获取地址信息 * @param $ip * @return mixed */ private function getAddressFromIp($ip){ $urlTaobao = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip; $urlSina = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip; $json = file_get_contents($urlTaobao); $jsonDecode = json_decode($json); if($jsonDecode->code==0){//如果取不到就去取新浪的 $data['country'] = $jsonDecode->data->country; $data['province'] = $jsonDecode->data->region; $data['city'] = $jsonDecode->data->city; $data['isp'] = $jsonDecode->data->isp; return $data; } else { $json = file_get_contents($urlSina); $jsonDecode = json_decode($json); $data['country'] = $jsonDecode->country; $data['province'] = $jsonDecode->province; $data['city'] = $jsonDecode->city; $data['isp'] = $jsonDecode->isp; $data['district'] = $jsonDecode->district; return $data; } }
方法2:


/** * 根据 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 = 'http://restapi.amap.com/v3/ip'; $data = array( 'output' => 'json', 'key' => '16199cf2aca1fb54d0db495a3140b8cb', 'ip' => $cip ); $postdata = http_build_query($data); $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); $res = json_decode($result, true); if (count($res['province']) == 0) { $res['province'] = '山东省'; } if (! empty($res['province']) && $res['province'] == "局域网") { $res['province'] = '山东省'; } if (count($res['city']) == 0) { $res['city'] = '临沂市'; } return $res; }
4、根据HTTP请求获取用户位置
/** * 根据HTTP请求获取用户位置 */ function getUserLocation() { $key = "16199cf2aca1fb54d0db495a3140b8cb"; // 高德地图key $url = "http://restapi.amap.com/v3/ip?key=$key"; $json = file_get_contents($url); $obj = json_decode($json, true); // 转换数组 $obj["message"] = $obj["status"] == 0 ? "失败" : "成功"; return $obj; }
利用mb_substr(),截取最后一个汉字:
$get_city='梧州市'; $get_city=mb_substr($get_city,0,strlen($get_city)-3); echo $get_city;
二、js常用的function
1、只允许数字,过滤掉输入的非数字
// input text 只允许数字 function number_only_blur(me) { var $me = $(me); var val = $me.val(); val = val.replace(/[^0-9]/g, ""); val = parseInt(val); val = isNaN(val) ? '' : val; if(val == 0) {val = '';} $me.val(val); }
********************************************
未整理:
<?php /** * PHP发送异步请求 * @author wangguibin * @date 2016-07-14 * @param string $url 请求地址 * @param array $param 请求参数 * @param string $httpMethod 请求方法GET或者POST * @return boolean * @link http://www.thinkphp.cn/code/71.html */ function makeRequest($url, $param, $httpMethod = 'POST') { $oCurl = curl_init(); curl_setopt($oCurl, CURLOPT_TIMEOUT, 5); curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 5); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); } if ($httpMethod == 'GET') { curl_setopt($oCurl, CURLOPT_URL, $url . "?" . http_build_query($param)); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); } else { curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($oCurl, CURLOPT_POST, 1); curl_setopt($oCurl, CURLOPT_POSTFIELDS, http_build_query($param)); } $this_header = array("content-type:application/x-www-form-urlencoded;charset=UTF-8"); curl_setopt($oCurl, CURLOPT_HTTPHEADER, $this_header); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); curl_close($oCurl); if (intval($aStatus["http_code"]) == 200) { return $sContent; } else { return FALSE; } } /** * * Enter 签名函数 * @param $paramArr */ function createSign($paramArr, $app_secret) { $sign = $app_secret; ksort($paramArr); foreach ($paramArr as $key => $val) { if ($key != '' && $val != '') { $sign .= $key . $val; } } $sign .= $app_secret; $sign = strtoupper(md5($sign)); return $sign; } /** * XSS过滤方法 * @param $val * @return $val */ function remove_xss($val) { // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed // this prevents some character re-spacing such as <java\0script> // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements, the user should never need these since they're normal characters // this prevents like <IMG SRC=@avascript:alert('XSS')> $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search .= '1234567890!@#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { // ;? matches the ;, which is optional // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars // @ @ search for the hex values $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ; // @ @ 0{0,7} matches '0' zero to seven times $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ; } // now the only remaining whitespace attacks are \t, \n, and \r $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) { $val_before = $val; for ($i = 0; $i < sizeof($ra); $i++) { $pattern = '/'; for ($j = 0; $j < strlen($ra[$i]); $j++) { if ($j > 0) { $pattern .= '('; $pattern .= '(&#[xX]0{0,8}([9ab]);)'; $pattern .= '|'; $pattern .= '|(�{0,8}([9|10|13]);)'; $pattern .= ')*'; } $pattern .= $ra[$i][$j]; } $pattern .= '/i'; $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags if ($val_before == $val) { // no replacements were made, so exit the loop $found = false; } } } return $val; } /** * 时间展示样式转换,根据时间转换为 **秒前, **分钟前, **小时前, **天前 * @param $the_time * @return $the_time */ function time_tran($the_time) { $now_time = date('Y-m-d H:i:s', time()); $now_time = strtotime($now_time); $show_time = strtotime($the_time); $dur = $now_time - $show_time; // if($dur < 0){ // return $the_time; // }else if($dur < 60) { // return $dur.'秒前'; // }else if($dur < 3600) { // return floor($dur/60).'分钟前'; // }else if ($dur < 86400) { // return floor($dur / 3600).'小时前'; // }else if ($dur < 259200) { // return floor($dur / 86400).'天前'; // } else { // return $the_time; // } $f = array( '31536000' => '年', '2592000' => '个月', '604800' => '星期', '86400' => '天', '3600' => '小时', '60' => '分钟', '1' => '秒' ); foreach ($f as $k => $v) { if (0 != $c = floor($dur / (int)$k)) { return $c . $v . '前'; } } return $the_time; } /** * 生成随机字符串,由小写英文和数字组成。去掉了容易混淆的0o1l之类 * @param int $int 生成的随机字串长度 * @param boolean $caps 大小写,默认返回小写组合。true为大写,false为小写 * @return string 返回生成好的随机字串 */ function randStr($int = 6, $caps = false) { $strings = '0123456789'; $return = ''; for ($i = 0; $i < $int; $i++) { srand(); $rnd = mt_rand(0, 9); $return = $return . $strings[$rnd]; } return $return; } /** * 遮掩函数 * @author wangguibin * @date 2016-08-08 * @param string $str 要遮掩的字符串 * @param int $int 遮掩的长度 * @return string 返回生成字串 */ function coverStr($str, $length = 8) { $string = ''; $arr = str_split($str, 1); $count = count($arr); if ($count <= $length) { $length = count($arr) / 2; } foreach ($arr as $k => $r) { if ($k + 1 <= ($count - $length) / 2 || $k + 1 > ($count - $length) / 2 + $length) { $string .= $r; } else { $string .= '*'; } } return $string; } /** * 简单加密解密方法,支持有效期 * @param string $string 原文或者密文 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE * @param string $key 密钥 * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 * @return string 处理后的原文,或者经过 base64_encode 处理后的密文 * * @example * * $a = authcode('abc', 'ENCODE', 'key'); * $b = authcode($a, 'DECODE', 'key'); // $b(abc) * * $a = authcode('abc', 'ENCODE', 'key', 3600); * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 */ function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) { $ckey_length = 4; // 随机密钥长度 取值 0-32; // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方 // 当此值为 0 时,则不产生随机密钥 $key = md5($key ? $key : 'luanxinmeiti'); $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya . md5($keya . $keyc); $key_length = strlen($cryptkey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for ($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for ($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if ($operation == 'DECODE') { if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc . str_replace('=', '', base64_encode($result)); } } /** * 识别终端访问类型 * @author wangguibin * @date 2016-08-10 * @return bool true:手机端 false:PC端 */ function check_wap() { if (isset($_SERVER['HTTP_VIA'])) { return true; } if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) { return true; } if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) { return true; } if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML") > 0) { $br = "WML"; } else { $browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : ''; if (empty($browser)) { return true; } $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, $browser) || checkSubstrs($mobile_token_list, $browser); if ($found_mobile) { $br = "WML"; } else { $br = "WWW"; } } if ($br == "WML") { return true; } else { return false; } } function checkSubstrs($list, $str) { $flag = false; for ($i = 0; $i < count($list); $i++) { if (strpos($str, $list[$i]) > 0) { $flag = true; break; } } return $flag; } /** * 字符串截取,支持中文和其他编码 * 引入该方法以解决 内置mb_substr方法截取字符串后不能显示省略号的不足 * @param string $str 需要转换的字符串 * @param int $start 开始位置 * @param string $length 截取长度 * @param string $charset 编码格式 * @param boolean $suffix 截断显示字符 * @return string */ function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) { if (function_exists("mb_substr")) { if ($suffix) { if ($str == mb_substr($str, $start, $length, $charset)) { return mb_substr($str, $start, $length, $charset); } else { return mb_substr($str, $start, $length, $charset) . "..."; } } else { return mb_substr($str, $start, $length, $charset); } } elseif (function_exists('iconv_substr')) { if ($suffix) { if ($str == iconv_substr($str, $start, $length, $charset)) { return iconv_substr($str, $start, $length, $charset); } else { return iconv_substr($str, $start, $length, $charset) . "..."; } } else { 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 . "…"; return $slice; } /** * 可以统计中文字符串长度的函数 * @param $str 要计算长度的字符串 * @param $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符 * @return int 字符串长度 * ex: * $str = '我们都是中国人啊,ye!'; * $len = abslength($str); * ar_dump($len); //return 12 * $len = abslength($str,'1'); * echo '<br />'.$len; //return 22 */ //header('Content-type:text/html;charset=utf-8'); function abslength($str) { if (empty($str)) { return 0; } if (function_exists('mb_strlen')) { return mb_strlen($str, 'utf-8'); } else { preg_match_all("/./u", $str, $ar); return count($ar[0]); } } /** * 测试打印方法 * PP * @param $val * @author:Lunan Developer * @date:2016-10-15 */ function PP($val) { echo "<pre>"; print_r($val); die; } /** * 写日志 * writeLog * @param $str_content 日志内容 * @param $str_log_file日志文件名 * @author:Lunan Developer * @date:2016-10-15 */ function writeLog($str_content, $str_log_file) { $path = RUNTIME_PATH."Logs/".date('Ymd').'/'; //判断是否存在logs目录,如果不存在则创建 if(!is_dir($path)){ @mkdir($path); @chmod($path, 0755); } error_log(date("c")."\t".$str_content."\n", 3, LOG_PATH.'/'.date('Ymd').'/'.$str_log_file); }
时间戳处理:
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 刘志淳 <chun@engineer.com> // +---------------------------------------------------------------------- namespace think\helper; date_default_timezone_set('Asia/Shanghai'); class Time { /** * 返回今日开始和结束的时间戳 * * @return array */ public static function today() { return [ mktime(0, 0, 0, date('m'), date('d'), date('Y')), mktime(23, 59, 59, date('m'), date('d'), date('Y')) ]; } /** * 返回昨日开始和结束的时间戳 * * @return array */ public static function yesterday() { $yesterday = date('d') - 1; return [ mktime(0, 0, 0, date('m'), $yesterday, date('Y')), mktime(23, 59, 59, date('m'), $yesterday, date('Y')) ]; } /** * 返回本周开始和结束的时间戳 * * @return array */ public static function week() { $timestamp = time(); return [ strtotime(date('Y-m-d', strtotime("+0 week Monday", $timestamp))), strtotime(date('Y-m-d', strtotime("+0 week Sunday", $timestamp))) + 24 * 3600 - 1 ]; } /** * 返回上周开始和结束的时间戳 * * @return array */ public static function lastWeek() { $timestamp = time(); return [ strtotime(date('Y-m-d', strtotime("last week Monday", $timestamp))), strtotime(date('Y-m-d', strtotime("last week Sunday", $timestamp))) + 24 * 3600 - 1 ]; } /** * 返回本月开始和结束的时间戳 * * @return array */ public static function month($everyDay = false) { return [ mktime(0, 0, 0, date('m'), 1, date('Y')), mktime(23, 59, 59, date('m'), date('t'), date('Y')) ]; } /** * 返回上个月开始和结束的时间戳 * * @return array */ public static function lastMonth() { $begin = mktime(0, 0, 0, date('m') - 1, 1, date('Y')); $end = mktime(23, 59, 59, date('m') - 1, date('t', $begin), date('Y')); return [$begin, $end]; } /** * 返回今年开始和结束的时间戳 * * @return array */ public static function year() { return [ mktime(0, 0, 0, 1, 1, date('Y')), mktime(23, 59, 59, 12, 31, date('Y')) ]; } /** * 返回去年开始和结束的时间戳 * * @return array */ public static function lastYear() { $year = date('Y') - 1; return [ mktime(0, 0, 0, 1, 1, $year), mktime(23, 59, 59, 12, 31, $year) ]; } public static function dayOf() { } /** * 获取几天前零点到现在/昨日结束的时间戳 * * @param int $day 天数 * @param bool $now 返回现在或者昨天结束时间戳 * @return array */ public static function dayToNow($day = 1, $now = true) { $end = time(); if (!$now) { list($foo, $end) = self::yesterday(); } return [ mktime(0, 0, 0, date('m'), date('d') - $day, date('Y')), $end ]; } /** * 返回几天前的时间戳 * * @param int $day * @return int */ public static function daysAgo($day = 1) { $nowTime = time(); return $nowTime - self::daysToSecond($day); } /** * 返回几天后的时间戳 * * @param int $day * @return int */ public static function daysAfter($day = 1) { $nowTime = time(); return $nowTime + self::daysToSecond($day); } /** * 天数转换成秒数 * * @param int $day * @return int */ public static function daysToSecond($day = 1) { return $day * 86400; } /** * 周数转换成秒数 * * @param int $week * @return int */ public static function weekToSecond($week = 1) { return self::daysToSecond() * 7 * $week; } private static function startTimeToEndTime() { } }
字符串处理:
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: yunwuxin <448901948@qq.com> // +---------------------------------------------------------------------- namespace think\helper; class Str { /** * 检查字符串中是否包含某些字符串 * @param string $haystack * @param string|array $needles * @return bool */ public static function contains($haystack, $needles) { foreach ((array)$needles as $needle) { if ($needle != '' && mb_strpos($haystack, $needle) !== false) { return true; } } return false; } /** * 检查字符串是否以某些字符串结尾 * * @param string $haystack * @param string|array $needles * @return bool */ public static function endsWith($haystack, $needles) { foreach ((array)$needles as $needle) { if ((string)$needle === static::substr($haystack, -static::length($needle))) { return true; } } return false; } /** * 检查字符串是否以某些字符串开头 * * @param string $haystack * @param string|array $needles * @return bool */ public static function startsWith($haystack, $needles) { foreach ((array)$needles as $needle) { if ($needle != '' && mb_strpos($haystack, $needle) === 0) { return true; } } return false; } /** * 获取指定长度的随机字母数字组合的字符串 * * @param int $length * @return string */ public static function random($length = 16) { $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return static::substr(str_shuffle(str_repeat($pool, $length)), 0, $length); } /** * 字符串转小写 * * @param string $value * @return string */ public static function lower($value) { return mb_strtolower($value, 'UTF-8'); } /** * 字符串转大写 * * @param string $value * @return string */ public static function upper($value) { return mb_strtoupper($value, 'UTF-8'); } /** * 获取字符串的长度 * * @param string $value * @return int */ public static function length($value) { return mb_strlen($value); } /** * 截取字符串 * * @param string $string * @param int $start * @param int|null $length * @return string */ public static function substr($string, $start, $length = null) { return mb_substr($string, $start, $length, 'UTF-8'); } }