Rumah > php教程 > PHP源码 > web开发中前、后端常用数据处理方法整理(集各家之言)

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

PHP中文网
Lepaskan: 2016-05-25 17:07:39
asal
1379 orang telah melayarinya

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(/\&#39;/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(/ /g, " ");   
  s = s.replace(/&#39;/g, "\&#39;");   
  s = s.replace(/&quot;/g, "\"");   
  s = s.replace(/<br>/g, "\n");   
  return s;   
}   
 
 
//使用ajax提交数据
function ajaxPost(the_url,the_param,succ_callback)
{
    $.ajax({
        type    : &#39;POST&#39;,
        cache   : false,
        url     : the_url,
        data    : the_param,
        success : succ_callback
    });
}
 
 
//使用ajax获取数据
 
function ajaxGet(the_url,succ_callback,error_callback)
{
    $.ajax({
        type    : &#39;GET&#39;,
        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        : &#39;post&#39;,
        dataType    : &#39;json&#39;,
        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  = &#39;z6OmlGsC9xqLPpN7iw8UDAb4HIBXfgEjJnrKZSeuV2Rt3yFcMWhakQT1oY5v0d&#39;;
        $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   = &#39;&#39;; 
         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),&#39;|&#39;);
        $str            = str_replace(array(&#39;&lt;&#39;, &#39;&gt;&#39;),array(&#39;<&#39;, &#39;>&#39;),$str);
        $str            = preg_replace("~<({$disallowable})[^>]*>(.*?<\s*\/(\\1)[^>]*>)?~is",&#39;$2&#39;,$str);
         
        return $str;
    }
    /**
     * 替换或转义标签
     * */
    function convert_tags($str)
    {
 
        if($str)
    //  $str = str_replace(array(&#39;&&#39;,&#39;<&#39;, &#39;>&#39;,"&#39;",&#39;"&#39;),array(&#39;&amp;&#39;,&#39;&lt;&#39;, &#39;&gt;&#39;,&#39;&#039;&#39;,&#39;&quot;&#39;),$str);
        $str = str_replace(array(&#39;<&#39;, &#39;>&#39;,"&#39;",&#39;"&#39;),array(&#39;&lt;&#39;, &#39;&gt;&#39;,&#39;&#039;&#39;,&#39;&quot;&#39;),$str);
        return $str;
    }
     
 
//    function jstrpos($haystack, $needle, $offset = null)
//    {
//          $needle  = trim($needle);
//      $jstrpos = false;
//      if(function_exists(&#39;mb_strpos&#39;))
//      {
//          $jstrpos = mb_strpos($haystack, $needle, $offset, self::$charset);
//      }
//      elseif(function_exists(&#39;strpos&#39;))
//      {
//          $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 = &#39;post&#39;)
    {
        $method = strtolower($method);
        if($method == &#39;get&#39; && !empty($vars))
        {
            if(strpos($url, &#39;?&#39;) === false)
                $url = $url . &#39;?&#39; . http_build_query($vars);
            else
                $url = $url . &#39;&&#39; . 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 == &#39;post&#39;) 
        {
            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 = &#39;[error:1]&#39;;
        }
         
        curl_close($ch);
        return $result;
         
    }
     
    /**
     * 获取客户端ip
     * */
    function getIp()
    {
        if (isset($_SERVER[&#39;HTTP_CLIENT_IP&#39;]))
        {
            return $_SERVER[&#39;HTTP_CLIENT_IP&#39;];
        }
        else if (isset($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]))
        {
            return $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;];
        }
        else if (isset($_SERVER[&#39;REMOTE_ADDR&#39;]))
        {
            return $_SERVER[&#39;REMOTE_ADDR&#39;];
        }
        return &#39;0.0.0&#39;;
    }
    /**
     * 图片大小验证器
     * $_FILES[&#39;file&#39;]数组
     * 
     * 只支持 jpg png gif 格式 默认5M
     * */
    function check_img($file,$limitSize=5242880)
    {
        $type_maping = array(1=>&#39;image/gif&#39;, 2=>&#39;image/jpeg&#39;, 3=>&#39;image/png&#39;,4=>&#39;image/pjpeg&#39;,5=>&#39;image/x-png&#39;,6=>&#39;image/jpg&#39;);
         
        if($file[&#39;size&#39;]>$limitSize)
        {
            $rs[&#39;error&#39;] = &#39;1&#39;;
            $rs[&#39;msg&#39;]   = &#39;图片超过规定大小!&#39;;
        }
        elseif($file[&#39;error&#39;]==4)
        {
            $rs[&#39;error&#39;] = &#39;1&#39;;
            $rs[&#39;msg&#39;]   = &#39;图片文件损害!&#39;;
        }
        elseif($file[&#39;size&#39;]==0)
        {
            $rs[&#39;error&#39;] = &#39;1&#39;;
            $rs[&#39;msg&#39;]   = &#39;空图片或者超过规定大小&#39;;
        }
        elseif( !in_array($file[&#39;type&#39;],$type_maping) )
        {
            $rs[&#39;error&#39;] = &#39;1&#39;;
            $rs[&#39;msg&#39;]   = &#39;图片类型错误!&#39;;
        }
        else
        {
            $rs[&#39;error&#39;] = &#39;no&#39;;
            $rs[&#39;msg&#39;]   = &#39;success&#39;;
        }
        return $rs;
    }
     
    /**
     * 递归方式的对变量中的特殊字符进行转义以及过滤标签
     */
    function addslashes_deep($value)
    {
        if (empty($value))return $value;
        //Huige 过滤html标签,防止sql注入
        return is_array($value) ? array_map(&#39;addslashes_deep&#39;, $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(&#39;stripslashes_deep&#39;, $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,&#39; &#39;));
            return (strlen($string) + mb_strlen($string,&#39;UTF-8&#39;)) / 4;
        }
        return false;
    }
    /**
     * 截取指定长度的字符串,超出部分用 ..替换
     * @param string $text
     * @param int $length
     * @param string $replace
     * @param string $encoding
     */
    function substr_format($text, $length, $replace=&#39;..&#39;, $encoding=&#39;UTF-8&#39;)
    {
        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(&#39;mb_convert_encoding&#39;)) {
            return mb_convert_encoding($source, $out, $in );
        }elseif (function_exists(&#39;iconv&#39;))  {
            return iconv($in,$out."//IGNORE", $source);
        }
        return $source;
    }
     
     
    /**
     *  Created:  2010-10-28
     *
     *  截取一定长度的字符串
     *  @Author guoliang1
     *
     ***************************************************/
     
    function cut_string($str, $len)
    {
        // 检查长度
        if (mb_strwidth($str, &#39;UTF-8&#39;)<=$len)
        {
            return $str;
        }
        // 截取
        $i      = 0;
        $tlen   = 0;
        $tstr   = &#39;&#39;;
     
        while ($tlen < $len)
        {
            $chr    = mb_substr($str, $i, 1, &#39;UTF-8&#39;);
            $chrLen = ord($chr) > 127 ? 2 : 1;
            if ($tlen + $chrLen > $len) break;
            $tstr .= $chr;
            $tlen += $chrLen;
            $i ++;
        }
     
        if ($tstr != $str)
        {
            $tstr .= &#39;...&#39;;
        }
     
        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=&#39;m月d日 H:i&#39;)
    {
        $now = time();
        $t   = $now - $time;
        if($t >= 3600)
        {
            if(date(&#39;Y&#39;)==date(&#39;Y&#39;,$time))
                $time =date($format,$time);
            else
                $time =date(&#39;Y年m月d日 H:i&#39;,$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] = &#39;周日&#39;;
        $date[1] = &#39;周一&#39;;
        $date[2] = &#39;周二&#39;;
        $date[3] = &#39;周三&#39;;
        $date[4] = &#39;周四&#39;;
        $date[5] = &#39;周五&#39;;
        $date[6] = &#39;周六&#39;;
        return $date[Date(&#39;w&#39;,$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));
    }
     
     
?>
Salin selepas log masuk

                   

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan