欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

web开发中前、后端常用数据处理方法整理(集各家之言)

程序员文章站 2022-05-13 21:01:25
...

1. [代码][PHP]代码

-------------------------   前端
/**
 *  前端公共函数方法整理 
 *  @author Weige 
 *  备注: 配合jqury.js 使用
 *  2012-04
 */
 
//获取字符串长度
function getWordSize(str)
{
    if(!str)
        return null;    
    var length = 0;
    var str = str;
    var regDoub = /[^x00-xff]/g;
    var regSingl = /[x00-xff]/g
    var douL = str.match(regDoub);
    var singL = str.match(regSingl)
    if(douL){
        length+=douL.length*2;
    }
    if(singL){
        length+=singL.length;
    }
    length/=2;
    length = Math.ceil(length);
    return length;
}
//祛除前后空格
function trim(str)
{
    return str.replace(/(^\s*)|(\s*$)/g, '');
}
//中文汉字编码判断
function isChinese(str)
{
  var str = str.replace(/(^\s*)|(\s*$)/g,'');
  if (!(/^[\u4E00-\uFA29]*$/.test(str)
          && (!/^[\uE7C7-\uE7F3]*$/.test(str))))
  {
      return false;
  }
  return true;
}
//手机判断
function isMobile(str)
{
 
    if(/^1[345689]\d{9}/.test(str))
      {
          return true;
      }
    return false;
 
}
// oschina
//特殊字符转换
function htmlEncode(str)   
{   
  var s = "";   
  if (str.length == 0) return "";  
  //s = s.replace(/ /g, " ");   
  s = str.replace(/&/g, "&");   
  s = s.replace(/</g, "&lt;");   
  s = s.replace(/>/g, "&gt;");   
  s = s.replace(/\'/g, "&#39;");   
  s = s.replace(/\"/g, "&quot;");   
  s = s.replace(/\n/g, "<br>");   
  return s;   
}   
 
function htmlDecode(str)   
{   
  var s = "";   
  if (str.length == 0) return "";   
  s = str.replace(/&gt;/g, "&");   
  s = s.replace(/&lt;/g, "<");   
  s = s.replace(/&gt;/g, ">");   
  s = s.replace(/&nbsp;/g, " ");   
  s = s.replace(/&#39;/g, "\'");   
  s = s.replace(/&quot;/g, "\"");   
  s = s.replace(/<br>/g, "\n");   
  return s;   
}   
 
 
//使用ajax提交数据
function ajaxPost(the_url,the_param,succ_callback)
{
    $.ajax({
        type    : 'POST',
        cache   : false,
        url     : the_url,
        data    : the_param,
        success : succ_callback
    });
}
 
 
//使用ajax获取数据
 
function ajaxGet(the_url,succ_callback,error_callback)
{
    $.ajax({
        type    : 'GET',
        cache   : true,
        url     : the_url,
        success : succ_callback,
        error   : error_callback
         
    });
}
 
//发送json格式数据
 
function ajaxPostJson(the_url,data_pro,succ_callback,error_callback)
{
    $.ajax({
        async       : false,//同步更新  
        type        : 'post',
        dataType    : 'json',
        data        : data_pro,
        url         : the_url,
        success     : succ_callback,
        error       : error_callback
        });
}
function real_len(name) 
{    
    return (name.replace(/[^\x00-\xff]/g,"**").length);    
}
 
function is_email(email)
{
    var reg=/^\s*([A-Za-z0-9_-]+(\.\w+)*@(\w+\.)+\w{2,3})\s*$/;
    return reg.test(email);
}
function is_number(name)
{
    var reg = /^\d+$/g;    
   return reg.test(name);    
}
function is_pwd(name)
{
     var reg = /^[A-Za-z@0-9_-]+$/g;    
  return reg.test(name);    
         
}
 
---------------------------------后端
 
 
<?php
 
 
    /**
     * Weige
     * 2012-05
     * */
     
    /**
     * 唯一名字
     * */
    function get_unique_name($srand_id=0) 
    {
        $id     = $srand_id?$srand_id:mt_rand(0,99999999);
        $index  = 'z6OmlGsC9xqLPpN7iw8UDAb4HIBXfgEjJnrKZSeuV2Rt3yFcMWhakQT1oY5v0d';
        $base   = 62;
        $out    = "";
         for ( $t = floor( log10( $id ) / log10( $base ) ); $t >= 0; $t-- ) 
         {
            $a      = floor( $id / pow( $base, $t ) );
            $out    = $out . substr( $index, $a, 1 );
            $id     = $id - ( $a * pow( $base, $t ) );
         }
       return $out;
    }
    /** 
     * 短链接密钥
     * */
    function url_key($url,$key="wei爱微博") 
    {
        $x      = sprintf("%u", crc32($key.$url)); 
        $show   = ''; 
         while($x> 0) 
         { 
             $s = $x% 62; 
             if($s> 35)
             $s = chr($s+61);             
             elseif($s> 9 && $s<=35)
             $s = chr($s+ 55); 
             $show.= $s; 
            $x  = floor($x/62); 
         } 
        return $show;     
    }
    /**
     * 标签key
     * */
    function tag_key($tag,$key="wei爱话题")
    {
        $tag = str_replace(" ", "", $tag);
        $tag.= $key;
        $hash = md5($tag);
        $hash = $hash[0] | ($hash[1] <<8 ) | ($hash[2] <<16) | ($hash[3] <<24) | ($hash[4] <<32) | ($hash[5] <<40) | ($hash[6] <<48) | ($hash[7] <<56);
        return $hash % 99999999;
     
    }
     
    /**
     * 过滤非法标签
     * */
    function strip_selected_tags($str,$disallowable="<script><iframe><style><link>")
    {
        $disallowable   = trim(str_replace(array(">","<"),array("","|"),$disallowable),'|');
        $str            = str_replace(array('&lt;', '&gt;'),array('<', '>'),$str);
        $str            = preg_replace("~<({$disallowable})[^>]*>(.*?<\s*\/(\\1)[^>]*>)?~is",'$2',$str);
         
        return $str;
    }
    /**
     * 替换或转义标签
     * */
    function convert_tags($str)
    {
 
        if($str)
    //  $str = str_replace(array('&','<', '>',"'",'"'),array('&amp;','&lt;', '&gt;','&#039;','&quot;'),$str);
        $str = str_replace(array('<', '>',"'",'"'),array('&lt;', '&gt;','&#039;','&quot;'),$str);
        return $str;
    }
     
 
//    function jstrpos($haystack, $needle, $offset = null)
//    {
//          $needle  = trim($needle);
//      $jstrpos = false;
//      if(function_exists('mb_strpos'))
//      {
//          $jstrpos = mb_strpos($haystack, $needle, $offset, self::$charset);
//      }
//      elseif(function_exists('strpos'))
//      {
//          $jstrpos = strpos($haystack, $needle, $offset);
//      }
//      return $jstrpos;
//    }
   /**
     * 检查是否为一个http开头并带有.com的url地址
     **/
    function is_http($url)
    {
        if(filter_var($url, FILTER_VALIDATE_URL))
        return true;return false;
    }
    /**
     * 发送一个http请求
     * @param  $url    请求链接
     * @param  $method 请求方式
     * @param array $vars 请求参数
     * @param  $time_out  请求过期时间
     * @return JsonObj
     */
    function get_curl($url, array $vars=array(), $method = 'post')
    {
        $method = strtolower($method);
        if($method == 'get' && !empty($vars))
        {
            if(strpos($url, '?') === false)
                $url = $url . '?' . http_build_query($vars);
            else
                $url = $url . '&' . http_build_query($vars);
        }
         
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     
        if ($method == 'post') 
        {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        }   
        $result = curl_exec($ch);
        if(!curl_errno($ch))
        {
            $result = trim($result);
        }
        else
        {
            $result = '[error:1]';
        }
         
        curl_close($ch);
        return $result;
         
    }
     
    /**
     * 获取客户端ip
     * */
    function getIp()
    {
        if (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            return $_SERVER['HTTP_CLIENT_IP'];
        }
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if (isset($_SERVER['REMOTE_ADDR']))
        {
            return $_SERVER['REMOTE_ADDR'];
        }
        return '0.0.0';
    }
    /**
     * 图片大小验证器
     * $_FILES['file']数组
     * 
     * 只支持 jpg png gif 格式 默认5M
     * */
    function check_img($file,$limitSize=5242880)
    {
        $type_maping = array(1=>'image/gif', 2=>'image/jpeg', 3=>'image/png',4=>'image/pjpeg',5=>'image/x-png',6=>'image/jpg');
         
        if($file['size']>$limitSize)
        {
            $rs['error'] = '1';
            $rs['msg']   = '图片超过规定大小!';
        }
        elseif($file['error']==4)
        {
            $rs['error'] = '1';
            $rs['msg']   = '图片文件损害!';
        }
        elseif($file['size']==0)
        {
            $rs['error'] = '1';
            $rs['msg']   = '空图片或者超过规定大小';
        }
        elseif( !in_array($file['type'],$type_maping) )
        {
            $rs['error'] = '1';
            $rs['msg']   = '图片类型错误!';
        }
        else
        {
            $rs['error'] = 'no';
            $rs['msg']   = 'success';
        }
        return $rs;
    }
     
    /**
     * 递归方式的对变量中的特殊字符进行转义以及过滤标签
     */
    function addslashes_deep($value)
    {
        if (empty($value))return $value;
        //Huige 过滤html标签,防止sql注入
        return is_array($value) ? array_map('addslashes_deep', $value) : strip_tags(addslashes($value));
    }
     
     
    /**
     * @param   mix     $value
     * @return  mix
     */
    function stripslashes_deep($value)
    {
        if (empty($value))return $value;
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }
     
    /**
     * 以新浪微博的字数统计方式统计字数(简单版)
     * 中文算1个,英文算0.5个,全角字符算1个,半角字符算0.5个。
     * @param string $string
     * @return integer
     */
    function strlen_weibo($string)
    {
        if(is_string($string))
        {
            $string=trim(trim($string,' '));
            return (strlen($string) + mb_strlen($string,'UTF-8')) / 4;
        }
        return false;
    }
    /**
     * 截取指定长度的字符串,超出部分用 ..替换
     * @param string $text
     * @param int $length
     * @param string $replace
     * @param string $encoding
     */
    function substr_format($text, $length, $replace='..', $encoding='UTF-8')
    {
        if ($text && mb_strlen($text, $encoding)>$length)
        {
            return mb_substr($text, 0, $length, $encoding).$replace;
        }
        return $text;
    }
    /**
     *
     * 字符编码转换
     *
     * */
    function xwb_iconv($source, $in, $out)
    {
        $in     = strtoupper($in);
        $out    = strtoupper($out);
        if ($in == "UTF8"){
            $in = "UTF-8";
        }
        if ($out == "UTF8"){
            $out = "UTF-8";
        }
        if($in==$out){
            return $source;
        }
     
        if(function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($source, $out, $in );
        }elseif (function_exists('iconv'))  {
            return iconv($in,$out."//IGNORE", $source);
        }
        return $source;
    }
     
     
    /**
     *  Created:  2010-10-28
     *
     *  截取一定长度的字符串
     *  @Author guoliang1
     *
     ***************************************************/
     
    function cut_string($str, $len)
    {
        // 检查长度
        if (mb_strwidth($str, 'UTF-8')<=$len)
        {
            return $str;
        }
        // 截取
        $i      = 0;
        $tlen   = 0;
        $tstr   = '';
     
        while ($tlen < $len)
        {
            $chr    = mb_substr($str, $i, 1, 'UTF-8');
            $chrLen = ord($chr) > 127 ? 2 : 1;
            if ($tlen + $chrLen > $len) break;
            $tstr .= $chr;
            $tlen += $chrLen;
            $i ++;
        }
     
        if ($tstr != $str)
        {
            $tstr .= '...';
        }
     
        return $tstr;
    }
    /**
     *  Created:  2010-10-28
     *
     *  防止XSS攻击,htmlspecialchars的别名
     *
     ***************************************************/
     
    function escape($str,  $quote_style = ENT_COMPAT )
    {
        return htmlspecialchars($str, $quote_style);
    }
    /**
     * 格式化时间
     *
     * */
    function wb_date_format($time,$format='m月d日 H:i')
    {
        $now = time();
        $t   = $now - $time;
        if($t >= 3600)
        {
            if(date('Y')==date('Y',$time))
                $time =date($format,$time);
            else
                $time =date('Y年m月d日 H:i',$time);
        }
        elseif ($t < 3600 && $t >= 60)
            $time = floor($t / 60) . "分钟前";
        else
            $time = "刚刚";
        return $time;
    }
     
    function isChinese($string)
    {
        if(preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$string))
            return true;
        return false;
    }
    function isMobile($mobile)
    {
        if(preg_match("/^1[345689]\d{9}$/", $mobile))
            return true;
        return false;
    }
    function dayToWeek($time)
    {
        $time = empty($time) ? TIME : $time;
        $date[0] = '周日';
        $date[1] = '周一';
        $date[2] = '周二';
        $date[3] = '周三';
        $date[4] = '周四';
        $date[5] = '周五';
        $date[6] = '周六';
        return $date[Date('w',$time)];
    }
     
    /**
     * 检测是否为邮箱
     * @param $val
     * @param $domain
     * @return boolean
     */
    function is_email($val,$domain="")
    {
        if(!$domain)
        {
            if( preg_match("/^[a-z0-9-_.]+@[\da-z][\.\w-]+\.[a-z]{2,4}$/i", $val) )
            return TRUE;
            return FALSE;
        }
 
        if( preg_match("/^[a-z0-9-_.]+@".$domain."$/i", $val) )
        return TRUE;
        return FALSE;
    }
    // junz先生
    //http://www.oschina.net/code/snippet_162279_7186
    //可逆加密
    function extend_decrypt($encryptedText,$key)
    {
        $cryptText      = base64_decode($encryptedText);
        $ivSize         = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv             = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $decryptText    = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
         
        return trim($decryptText);
    }
    //http://www.oschina.net/code/snippet_162279_7186
    //可逆解密
    function extend_encrypt($plainText,$key)
    {
        $ivSize         = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv             = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $encryptText    = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
         
        return trim(base64_encode($encryptText));
    }
     
     
?>