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)做用:取得隨機字符串
 * 參數:
 * 一、(int)$length = 32 #隨機字符長度
 * 二、(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)."'";
相關文章
相關標籤/搜索