php常用函数
(1)php判断检测一个数组里有没有重复的值 if (count($array) != count(array_unique($array))) { echo '该数组有重复值'; } (2)处理从前端传来的json数据 public function dealJson($param){ return json_decode(htmlspecialchars_decode($param), true); } (3)字符串转条件 public static function str2where($condition) { if (self::check_condition($condition)) { $condition = preg_replace('/^(and|or)/i', '', $condition); $condition = str_replace(array('--', '__'), array(' ', "' "), $condition); $old_char = array(' ne ', ' eq ', ' lt ', ' gt ', ' le ', ' ge ', ' ct ', ' nct '); $new_char = array(" != '", " = '", " < '", " > '", " <= '", " >= '", " like '%", " not like '%"); $condition = str_replace($old_char, $new_char, $condition); $condition = preg_replace("/\s+(like\s+'[^']+)('|$)/i", " $1%$2", $condition); if ($condition != '') $condition .= "'"; return $condition; } return null; } (4)获取汉字首字母 public function getFirstCharter($str){ if (empty($str)) { return ''; } $fchar = ord($str{0}); if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0}); $s1 = iconv('UTF-8', 'gb2312', $str); $s2 = iconv('gb2312', 'UTF-8', $s1); $s = $s2 == $str ? $s1 : $str; $asc = ord($s{0}) * 256 + ord($s{1}) - 65536; if ($asc >= -20319 && $asc <= -20284) return 'A'; if ($asc >= -20283 && $asc <= -19776) return 'B'; if ($asc >= -19775 && $asc <= -19219) return 'C'; if ($asc >= -19218 && $asc <= -18711) return 'D'; if ($asc >= -18710 && $asc <= -18527) return 'E'; if ($asc >= -18526 && $asc <= -18240) return 'F'; if ($asc >= -18239 && $asc <= -17923) return 'G'; if ($asc >= -17922 && $asc <= -17418) return 'H'; if ($asc >= -17417 && $asc <= -16475) return 'J'; if ($asc >= -16474 && $asc <= -16213) return 'K'; if ($asc >= -16212 && $asc <= -15641) return 'L'; if ($asc >= -15640 && $asc <= -15166) return 'M'; if ($asc >= -15165 && $asc <= -14923) return 'N'; if ($asc >= -14922 && $asc <= -14915) return 'O'; if ($asc >= -14914 && $asc <= -14631) return 'P'; if ($asc >= -14630 && $asc <= -14150) return 'Q'; if ($asc >= -14149 && $asc <= -14091) return 'R'; if ($asc >= -14090 && $asc <= -13319) return 'S'; if ($asc >= -13318 && $asc <= -12839) return 'T'; if ($asc >= -12838 && $asc <= -12557) return 'W'; if ($asc >= -12556 && $asc <= -11848) return 'X'; if ($asc >= -11847 && $asc <= -11056) return 'Y'; if ($asc >= -11055 && $asc <= -10247) return 'Z'; return null; } (5)验证手机号 public function IsMobile($string){ $rule = "/^((13[0-9])|170|147|(15[0-35-9])|(18[0-9]))[0-9]{8}$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (6)座机号码验证 public function IsPhone($string){ $rule = "/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (7)邮编号码验证 public function IsPostCode($string){ $rule = "/^[0-9]{6}$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (8)邮箱验证 public function IsEmail($string){ $rule = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (9)验证是否为数字 public function IsNumber($string){ $rule = "/^[1-9]\d*$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (10)验证小数点 public function CheckPoints($str){ if(ceil($str)==$str && floor($str)==$str){ return true; }else{ if (!ereg("^[0-5][.][0-9]{1,}", $str)) { return false; }else{ return true; } } } (11)验证金额是否正确 public function MoneyIsCorrect($string){ $rule = "/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/"; if(!preg_match($rule,$string)){ return false; }else{ return true; } } (12) 校验日期格式是否正确 public function IsDate($date, $format = 'Y-m-d H:i:s') { $unixTime = strtotime($date); if (!$unixTime) { //strtotime转换不对,日期格式显然不对。 return false; } //校验日期的有效性,只要满足其中一个格式就OK if (date($format, $unixTime) == $date) { return true; } return false; } (13)验证URL地址是否合法 public function check_url($url){ $pattern_3='/^http[s]?:\/\/'. '(([0-9]{1,3}\.){3}[0-9]{1,3}'. '|'. '([0-9a-z_!~*\'()-]+\.)*'. '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.'. '[a-z]{2,6})'. '(:[0-9]{1,4})?'. '((\/\?)|'. '(\/[0-9a-zA-Z_!~\*\'\(\)\.;\?:@&=\+\$,%#-\/]*)?)$/'; if(preg_match($pattern_3, $url)){ return ture; } else{ return false; } } (14)格式化保留两位小数 function normal_number_format($v) { if(empty($v)) { return '0.00'; } if(!is_numeric($v)) { return 'NaN'; } return number_format($v,2,'.',','); } (15)从html中获取图片地址 public function get_img_html($str){ $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";//取src preg_match_all($pattern,$str,$match); if(isset($match[1])&&!empty($match[1])){ return $match[1]; } return ''; } (16)从字符串中获取http开头的地址 public function get_http_url($str){ $pattern='/https?:[^"]+/'; preg_match_all($pattern,$str,$match); if(isset($match[0])){ return $match[0]; } return ''; } (17)验证是否为微信浏览器 public function IsWechat() { $agent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : null; return (strpos($agent, 'micromessenger') !== false); } (18)验证是否为IOS public function IsIOS() { $agent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : null; return (strpos($agent, 'iphone') !== false); } /* (19)作用:取得随机字符串 * 参数: * 1、(int)$length = 32 #随机字符长度 * 2、(int)$mode = 0 #随机字符类型,0为大小写英文和数字,1为数字,2为小写字母,3为大写字母, 4为大小写字母,5为大写字母和数字,6为小写字母和数字 * 返回:取得的字符串 */ public function get_code($length = 32, $mode = 0) {//获取随机验证码函数 switch ($mode) { case '1': $str = '0123456789'; break; case '2': $str = 'abcdefghijklmnopqrstuvwxyz'; break; case '3': $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case '4': $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; break; case '5': $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; break; case '6': $str = 'abcdefghijklmnopqrstuvwxyz1234567890'; break; default: $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; break; } $checkstr = ''; $len = strlen($str) - 1; for ($i = 0; $i < $length; $i++) { $num = mt_rand(0, $len); //产生一个0到$len之间的随机数 $checkstr.=$str[$num]; } return $checkstr; } (20)生成订单编号 public static function createOrderNo() { return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6); } /** * (21)获取唯一编号号 * @param mixed $sql_model * $c:前缀,$table:表名,$prefiel:字段 * @return string */ public function GetNum($c,$table,$prefiel){ $cdh=date('YmdHis',strtotime($this->GetDateTimeMk(time()))); $lscdh=substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); $rdh=$c.substr($cdh,0,12).$lscdh; //判断编号号是否被占用 $table_m=M($table); $rowcount=$table_m->where('"{$prefiel}"="'.$rdh.'"')->count(); if($rowcount>0){ $rdh=$this->GetNum(); } return $rdh; } (22)创建短链接 public function shortUrl($url){ $base32 = 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', '0', '1', '2', '3', '4', '5' ); $hex = md5($url); $hexLength = strlen($hex); $subHexLen = $hexLength / 8; $output = array(); for ($i = 0; $i < $subHexLen; $i++) { //每循环一次取到8位 $subHex = substr ($hex, $i * 8, 8); $int = 0x3FFFFFFF & (1 * ('0x'.$subHex)); $out = ''; for ($j = 0; $j < 6; $j++) { $val = 0x0000001F & $int; $out .= $base32[$val]; $int = $int >> 5; } $output[] = $out; } $re=$this->chechkShortUrl($output['0']); if($re){ $this->shortUrl($url); } return $output[0]; } // 验证短链接是否唯一 public function chechkShortUrl($url){ $count=M('promotion_real_url')->where('short_url="'.$url.'"')->count(); if($count==0){ return false;//如果短链接不存在,则返回上面 } return true;//如果存在,则返回短链接 } (23)敏感词过滤 public function removeBadWords($badWord){ $badword = C('bad_words'); $badword1 = array_combine($badword,array_fill(0,count($badword),'***')); $str = strtr($badWord, $badword1); return $str; }
(24)匹配可能包含中文、英文、数字的字符串,中文最多16个字符,英文+字母之和最多32 /* * @desc 匹配可能包含中文、英文、数字的字符串,中文最多16个字符,英文+字母之和最多32 * @param $str string 待匹配的字符串 * @param $len int 匹配字符串的字符数(一个汉字占2个字节) */ public function isPreg($str){ preg_match_all("/[0-9]{1}/",$str,$arrNum); //匹配数字 preg_match_all("/[a-zA-Z]{1}/",$str,$arrAl); //匹配字母 preg_match_all("/([\x{4e00}-\x{9fa5}]){1}/u", $str, $arrCh); //匹配汉字 $c1=count($arrNum[0]); //数字个数 $c2=count($arrAl[0]); //字母个数 $c3=count($arrCh[0]); //汉字个数 $cz1=$c1+$c2; //字母+数字总数 $c4=(int)(($len-$cz1)/2); if($c3 > $c4){ return false; } return true; }
(25)验证版本号 3.6.7 if(!preg_match("/^[1-9]{1,2}[.]{1}[0-9]{1,2}[.]{1}[0-9]{1,2}$/",$version_name)){ $data = array('msg' =>"app版本名称格式不正确!" , 'status'=>'1','result'=>null); $this->ajaxReturn($data); }
(26)将一个二维数组合并成一个一维数组 public function merge_array($array){ return call_user_func_array('array_merge',$array); }
(27)二维数组去重 public function remove_duplicate($array){ $result=array(); foreach ($array as $key => $value) { $has = false; foreach($result as $val){ if($val['product_id']==$value['product_id']){ $has = true; break; } } if(!$has) $result[]=$value; } return $result; }
(28) public function getTreeInfo($cats){ $cn=count($cats); $a1=$arr[]=$cats[0].'/'.$cats[1]; if($cn > 2){ for($i=2;$i<$cn;$i++){ $a1 .='/'.$cats[$i]; $arr[]=$a1; } } return $arr; } //调用实例$where ="is_deleted=1 and is_open=1 and sku_no in ($sku_no) and pt_cats='0/1'"; $store_goods_info=$store_goods->field('id,g_cats')->where($where)->select(); $g_cats=array_merge(array_unique(array_column($store_goods_info,'g_cats'))); $cs=count($g_cats); for($i=0;$i<$cs;$i++){ $cats[$i]=explode('/',$g_cats[$i]); } foreach($cats as $k=>$v){ $arr[$k]=$this->getTreeInfo($v); } $data=$this->merge_array($arr); $cats_info=array_unique($data);
(29)金额格式化 public function formatMoney($money){ $money=empty($money)?'0.00':number_format($money,4,".",""); $money=rtrim(rtrim($money, '0'), '.'); if(ceil($money)==$money){ $money .=".00"; } return $money; } /**************************************************** 1)若第4位小数是0,则 第4位小数不显示;(例:8.8880,显示:8.888) 2)若第3位 和 第4位小数 都是0,则 第3位和第4位都不显示; (例:8.8800,显示:8.88) 3)至少显示两位小数,即使第1位 和 第2位小数都是0;也需要显示; (例:8.0000,显示:8.00) ****************************************************/
(30)把过长的字符只显示规定的几个后面用省略号代替 function cut_str($str,$len,$suffix="..."){ if(function_exists('mb_substr')){ if(strlen($str) > $len){ $str= mb_substr($str,0,$len).$suffix; } return $str; }else{ if(strlen($str) > $len){ $str= substr($str,0,$len).$suffix; } return $str; } }
(31)获取所有 以 HTTP开头的header参数 function getAllHeadersParam(){ $headers = array(); foreach($_SERVER as $key=>$value){ if(substr($key, 0, 5)==='HTTP_'){ $key = substr($key, 5); $key = str_replace('_', ' ', $key); $key = str_replace(' ', '-', $key); $key = strtolower($key); $headers[$key] = $value; } } return $headers; }
(32)多维数组排序
public function sortArrByOneField(&$array, $field, $desc = false){
$fieldArr = array();
foreach ($array as $k => $v) {
$fieldArr[$k] = $v[$field];
}
$sort = $desc == false ? SORT_ASC : SORT_DESC;
array_multisort($fieldArr, $sort, $array);
}
(33)函数转字符串处理
$user_ids=implode(",",array_unique(array_column($customer_info2,'user_id')));
$user_ids = "'".str_replace(",","','",$user_ids)."'";