• php常用函数


    /
     ****php常用函数
    /
    1、加密解密字符串
    function encryptDecrypt($key, $string, $decrypt){
        if($decrypt){
            $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
            return $decrypted;
        }else{
            $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
            return $encrypted;
        }
    }
    //以下是将字符串“Helloweba欢迎您”分别加密和解密
    //加密:
    echo encryptDecrypt('password', 'Helloweba欢迎您',0);
    //解密:
    echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);
     
     
    2、php生成随机字符串   字母和数字的集合  
    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
     
    3、php获取文件后缀名
    function getExtension($filename){
      $myext = substr($filename, strrpos($filename, '.'));
      return str_replace('.','',$myext);
    }
    4、php获取文件大小并格式化   以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。
    function formatSize($size) {
        $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
        if ($size == 0) { 
            return('n/a'); 
        } else {
          return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); 
        }
    }
     
    //$thefile = filesize('test_file.mp3'); 
     
    5、php替换字符标签
    function stringParser($string,$replacer){
        $result = str_replace(array_keys($replacer), array_values($replacer),$string);
        return $result;
    }
     
    $string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
    $replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');
    echo stringParser($string,$replace_array);
     
     
     
    6、php列出文件夹下的所有文件名
     
    function listDirFiles($DirPath){
        if($dir = opendir($DirPath)){
             while(($file = readdir($dir))!== false){
                    if(!is_dir($DirPath.$file))
                    {
                        echo "filename: $file<br />";
                    }
             }
        }
    }
     
    //listDirFiles('home/some_folder/');
     
    7、php获取当前网页的url
    function curPageURL() {
        $pageURL = 'http';
        if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
     
    echo curPageURL();
     
     
     
    8、php强制下载文件
    function download($filename){
        if ((isset($filename))&&(file_exists($filename))){
           header("Content-length: ".filesize($filename));
           header('Content-Type: application/octet-stream');
           header('Content-Disposition: attachment; filename="' . $filename . '"');
           readfile("$filename");
        } else {
           echo "Looks like file does not exist!";
        }
    }
    download('/down/test_45f73e852.zip');
     
    9、php字符串的截取  限制长度后用'...'显示
    /*
     Utf-8、gb2312都支持的汉字截取函数
     cut_str(字符串, 截取长度, 开始长度, 编码);
     编码默认为 utf-8
     开始长度默认为 0
    */
    function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
        if($code == 'UTF-8'){
            $pa = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/";
            preg_match_all($pa, $string, $t_string);
     
            if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
            return join('', array_slice($t_string[0], $start, $sublen));
        }else{
            $start = $start*2;
            $sublen = $sublen*2;
            $strlen = strlen($string);
            $tmpstr = '';
     
            for($i=0; $i<$strlen; $i++){
                if($i>=$start && $i<($start+$sublen)){
                    if(ord(substr($string, $i, 1))>129){
                        $tmpstr.= substr($string, $i, 2);
                    }else{
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if(ord(substr($string, $i, 1))>129) $i++;
            }
            if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
            return $tmpstr;
        }
    }
    $str = "jQuery插件实现的加载图片和页面效果";
    echo cutStr($str,16);
     
    10、PHP获取客户端真实IP
    //获取用户真实IP
    function getIp() {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else
            if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            else
                if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                    $ip = getenv("REMOTE_ADDR");
                else
                    if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                        $ip = $_SERVER['REMOTE_ADDR'];
                    else
                        $ip = "unknown";
        return ($ip);
    }
    echo getIp();
     
    11、随机颜色生成器
        function rabdowColor(){
           $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
            $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
            return $color;
    }
    //$color =rabdowColor();
     
    12、二维数组去重函数
      function unique($data = array()){
                $tmp = array();
                foreach($data as $key => $value){
                    //把一维数组键值与键名组合
                    foreach($value as $key1 => $value1){
                        $value[$key1] = $key1 . '_|_' . $value1;//_|_分隔符复杂点以免冲突
                    }
                    $tmp[$key] = implode(',|,', $value);//,|,分隔符复杂点以免冲突
                }
     
                //对降维后的数组去重复处理
                $tmp = array_unique($tmp);
     
                //重组二维数组
                $newArr = array();
                foreach($tmp as $k => $tmp_v){
                    $tmp_v2 = explode(',|,', $tmp_v);
                    foreach($tmp_v2 as $k2 => $v2){
                        $v2 = explode('_|_', $v2);
                        $tmp_v3[$v2[0]] = $v2[1];
                    }
                    $newArr[$k] = $tmp_v3;
                }
                return $newArr;
            }
            $newArr = unique($list);
     
     
    13、截取两个字符之间的内容
    function strCutByStr(&$str, $findStart, $findEnd = false, $encoding = 'utf-8'){  
                if(is_array($findStart)){  
                    if(count($findStart) === count($findEnd)){  
                        foreach($findStart as $k => $v){  
                            if(($result = strCutByStr($str, $v, $findEnd[$k], $encoding)) !== false){  
                                return $result;  
                            }  
                        }  
                        return false;  
                    }else{  
                        return false;  
                    }  
                }  
     
                if(($start = mb_strpos($str, $findStart, 0, $encoding)) === false){  
                    return false;  
                }  
     
                $start += mb_strlen($findStart, $encoding);  
     
                if($findEnd === false){  
                    return mb_substr($str, $start, NULL, $encoding);  
                }  
     
                if(($length = mb_strpos($str, $findEnd, $start, $encoding)) === false){  
                    return false;  
                }  
     
                return mb_substr($str, $start, $length - $start, $encoding);  
            }  
     
     
        $str = '1那是一场23我问问4567890维稳';  
     
        echo (strCutByStr($str, '那是', '稳'));//输出 一场23我问问4567890维
    此内容为网上的内容,如有侵权请联系删除,谢谢。
  • 相关阅读:
    systemd管理服务
    卷积神经网络
    matplotlib-3.2.1
    pandas-1.0.3
    numpy-1.18.4
    降维
    无监督学习-聚类
    集成学习
    人工神经网络
    贝叶斯分类
  • 原文地址:https://www.cnblogs.com/shuangzikun/p/taotao_php_function.html
Copyright © 2020-2023  润新知