超好用PHP函数库~不断更新,欢迎评论补充!(精)

6 篇文章 0 订阅
4 篇文章 0 订阅

平时工作需要经常需要用到一些函数,其实可以很好的封装,但发现PHP内置函数太过基础,实际用的稍不注意就容易出问题,最近我用的截取字符串函数substr但截取中文的时候容易截取不全导致乱码,所以在这里我把我平时自己写的函数都放在这里供大家取用,转载请注明出处,谢谢配合~

1. 完整截取中文字符串,混合字符串防止乱码:

function xsubstr($str,$start = 0,$length,$charset = "utf-8",$suffix = TRUE)
{
    if(function_exists("mb_substr")){
        $slice = mb_substr($str,$start,$length,$charset);
    }elseif(function_exists('iconv_substr')){
        $slice = iconv_substr($str,$start,$length,$charset);
        if(FALSE===$slice){
            $slice = '';
        }
    }else{
        $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset],$str,$match);
        $slice = join("",array_slice($match[0],$start,$length));
    }
    return $suffix?$slice.'...':$slice;
}

2. 判断是否手机端访问函数:

function isMobile()
{

    $user_agent = isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:'';

    $mobile_agents = Array(
        "240x320",
        "acer",
        "acoon",
        "acs-",
        "abacho",
        "ahong",
        "airness",
        "alcatel",
        "amoi",
        "android",
        "anywhereyougo.com",
        "applewebkit/525",
        "applewebkit/532",
        "asus",
        "audio",
        "au-mic",
        "avantogo",
        "becker",
        "benq",
        "bilbo",
        "bird",
        "blackberry",
        "blazer",
        "bleu",
        "cdm-",
        "compal",
        "coolpad",
        "danger",
        "dbtel",
        "dopod",
        "elaine",
        "eric",
        "etouch",
        "fly ",
        "fly_",
        "fly-",
        "go.web",
        "goodaccess",
        "gradiente",
        "grundig",
        "haier",
        "hedy",
        "hitachi",
        "htc",
        "huawei",
        "hutchison",
        "inno",
        "ipad",
        "ipaq",
        "ipod",
        "jbrowser",
        "kddi",
        "kgt",
        "kwc",
        "lenovo",
        "lg ",
        "lg2",
        "lg3",
        "lg4",
        "lg5",
        "lg7",
        "lg8",
        "lg9",
        "lg-",
        "lge-",
        "lge9",
        "longcos",
        "maemo",
        "mercator",
        "meridian",
        "micromax",
        "midp",
        "mini",
        "mitsu",
        "mmm",
        "mmp",
        "mobi",
        "mot-",
        "moto",
        "nec-",
        "netfront",
        "newgen",
        "nexian",
        "nf-browser",
        "nintendo",
        "nitro",
        "nokia",
        "nook",
        "novarra",
        "obigo",
        "palm",
        "panasonic",
        "pantech",
        "philips",
        "phone",
        "pg-",
        "playstation",
        "pocket",
        "pt-",
        "qc-",
        "qtek",
        "rover",
        "sagem",
        "sama",
        "samu",
        "sanyo",
        "samsung",
        "sch-",
        "scooter",
        "sec-",
        "sendo",
        "sgh-",
        "sharp",
        "siemens",
        "sie-",
        "softbank",
        "sony",
        "spice",
        "sprint",
        "spv",
        "symbian",
        "tablet",
        "talkabout",
        "tcl-",
        "teleca",
        "telit",
        "tianyu",
        "tim-",
        "toshiba",
        "tsm",
        "up.browser",
        "utec",
        "utstar",
        "verykool",
        "virgin",
        "vk-",
        "voda",
        "voxtel",
        "vx",
        "wap",
        "wellco",
        "wig browser",
        "wii",
        "windows ce",
        "wireless",
        "xda",
        "xde",
        "zte"
    );

    $is_mobile = FALSE;

    foreach($mobile_agents as $device){
        if(stristr($user_agent,$device)){
            $is_mobile = TRUE;
            break;
        }
    }

    return $is_mobile;
}

3. 判断是否UTF-8:

function is_utf8($liehuo_net)
{
    if(preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$liehuo_net)==TRUE||preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$liehuo_net)==TRUE||preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$liehuo_net)==TRUE){
        return TRUE;
    }else{
        return FALSE;
    }
}

4. 发送短信到手机:

function sendSMS($telphone,$message,$sign_name = "sign_name",$sendtime = '')
{
    $flag = 0;
    $sms  = F('sms');
    $argv = array(
        'sn'      => $sms['uid'],
        'pwd'     => strtoupper(md5($sms['uid'].$sms['passwd'])),
        'mobile'  => $telphone,
        'content' => urlencode($message.'【'.$sms[$sign_name].'】'),
        'ext'     => '',
        'rrid'    => '',
        'stime'   => $sendtime
    );
    foreach($argv as $key => $value){
        if($flag!=0){
            $params .= "&";
            $flag = 1;
        }
        $params .= $key."=";
        $params .= urlencode($value);
        $flag = 1;
    }
    $length = strlen($params);
    $fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno);
    $header = "POST /webservice.asmx/mdSmsSend_u HTTP/1.1\r\n";
    $header .= "Host:sdk2.entinfo.cn\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: ".$length."\r\n";
    $header .= "Connection: Close\r\n\r\n";
    $header .= $params."\r\n";
    fputs($fp,$header);
    $inheader = 1;
    while(!feof($fp)){
        $line = fgets($fp,1024);
        if($inheader&&($line=="\n"||$line=="\r\n")){
            $inheader = 0;
        }
        if($inheader==0){
        }
    }

    preg_match('/<string xmlns=\"http:\/\/tempuri.org\/\">(.*)<\/string>/',$line,$str);
    $result = explode("-",$str[1]);

    if(count($result)>1){
        //echo '发送失败返回值为:'.$line."请查看webservice返回值";
        return $line;
    }else{
        //echo '发送成功 返回值为:'.$line;
        return 1;
    }
}

5. 群发短信到手机:

//多条短信 最多600条
//发送到目标手机号码字符串 用","隔开 $telphone手机号码 $message短信内容
function sendGroupSMS($telphone,$message,$sign_name = "sign_name",$sendtime = '')
{
    $flag = 0;
    $sms  = F('sms');
    //要post的数据
    $argv = array(
        'sn'      => $sms['uid'],
        替换成您自己的序列号
        'pwd'     => strtoupper(md5($sms['uid'].$sms['passwd'])),
        //此处密码需要加密 加密方式为 md5(sn+password) 32位大写
        'mobile'  => $telphone,
        //手机号 多个用英文的逗号隔开 post理论没有长度限制.推荐群发一次小于等于10000个手机号
        'content' => urlencode($message.'【'.$sms[$sign_name].'】'),
        //短信内容
        'ext'     => '',
        'rrid'    => '',
        //默认空 如果空返回系统生成的标识串 如果传值保证值唯一 成功则返回传入的值
        'stime'   => $sendtime
        //定时时间 格式为2011-6-29 11:09:21
    );
    //构造要post的字符串
    foreach($argv as $key => $value){
        if($flag!=0){
            $params .= "&";
            $flag = 1;
        }
        $params .= $key."=";
        $params .= urlencode($value);
        $flag = 1;
    }
    $length = strlen($params);
    //创建socket连接
    $fp = fsockopen("sdk2.entinfo.cn",8060,$errno,$errstr,10) or exit($errstr."--->".$errno);
    //构造post请求的头
    $header = "POST /webservice.asmx/mdSmsSend_u HTTP/1.1\r\n";
    $header .= "Host:sdk2.entinfo.cn\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: ".$length."\r\n";
    $header .= "Connection: Close\r\n\r\n";
    //添加post的字符串
    $header .= $params."\r\n";
    //发送post的数据
    fputs($fp,$header);
    $inheader = 1;
    while(!feof($fp)){
        $line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
        if($inheader&&($line=="\n"||$line=="\r\n")){
            $inheader = 0;
        }
        if($inheader==0){
            // echo $line;
        }
    }

    preg_match('/<string xmlns=\"http:\/\/tempuri.org\/\">(.*)<\/string>/',$line,$str);
    $result = explode("-",$str[1]);

    if(count($result)>1){
        //echo '发送失败返回值为:'.$line."请查看webservice返回值";
        return $line;
    }else{
        //echo '发送成功 返回值为:'.$line;
        return 1;
    }
}

6. 判断目录是否可写:

//判断目录是否可写
function check_dir_iswritable($dir_path)
{
    $dir_path   = str_replace('\\','/',$dir_path);
    $is_writale = 1;
    if(!is_dir($dir_path)){
        $is_writale = 0;
        return $is_writale;
    }else{
        $file_hd = @fopen($dir_path.'/test.txt','w');
        if(!$file_hd){
            @fclose($file_hd);
            @unlink($dir_path.'/test.txt');
            $is_writale = 0;
            return $is_writale;
        }
        @unlink($dir_path.'/test.txt');
        $dir_hd = opendir($dir_path);
        while(FALSE!==($file = readdir($dir_hd))){
            if($file!="."&&$file!=".."){
                if(is_file($dir_path.'/'.$file)){
                    //文件不可写,直接返回
                    if(!is_writable($dir_path.'/'.$file)){
                        return 0;
                    }
                }else{
                    $file_hd2 = @fopen($dir_path.'/'.$file.'/test.txt','w');
                    if(!$file_hd2){
                        @fclose($file_hd2);
                        @unlink($dir_path.'/'.$file.'/test.txt');
                        $is_writale = 0;
                        return $is_writale;
                    }
                    @unlink($dir_path.'/test.txt');
                    //递归
                    $is_writale = check_dir_iswritable($dir_path.'/'.$file);
                }
            }
        }
    }
    return $is_writale;
}

7. 邮箱验证:

function is_email($email)
{
    return strlen($email)>8&&preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i",$email);
}

8. 手机验证:

function is_phone($phone)
{
    return strlen(trim($phone))==11&&preg_match("/^1[3|5|8][0-9]{9}$/i",trim($phone));
}

9. 下载:

function download($file,$name = '')
{
    $fileName = $name?$name:pathinfo($file,PATHINFO_FILENAME);
    $filePath = realpath($file);

    $fp = fopen($filePath,'rb');

    if(!$filePath||!$fp){
        header('HTTP/1.1 404 Not Found');
        echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding -->
            <!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->
            <!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
        exit;
    }

    $fileName         = $fileName.'.'.pathinfo($filePath,PATHINFO_EXTENSION);
    $encoded_filename = urlencode($fileName);
    $encoded_filename = str_replace("+","%20",$encoded_filename);

    header('HTTP/1.1 200 OK');
    header("Pragma: public");
    header("Expires: 0");
    header("Content-type: application/octet-stream");
    header("Content-Length: ".filesize($filePath));
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($filePath));

    $ua = isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:'';
    if(preg_match("/MSIE/",$ua)){
        header('Content-Disposition: attachment; filename="'.$encoded_filename.'"');
    }else{
        if(preg_match("/Firefox/",$ua)){
            header('Content-Disposition: attachment; filename*="utf8\'\''.$fileName.'"');
        }else{
            header('Content-Disposition: attachment; filename="'.$fileName.'"');
        }
    }

    // ob_end_clean(); <--有些情况可能需要调用此函数
    // 输出文件内容
    fpassthru($fp);
    exit;
}

10. 过滤特殊字符:

/*
 * 处理提交的字符串
 */
function strFilter($str){
    $str=preg_replace("/\/|\~|\s+|\!|\?|\/|\±|\@|\#|\\$|\%|\^|\"|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/"," ",$str);
    $str = str_replace(PHP_EOL, ' ', $str);
    //替换非英语字符
    $str_replace1 = array("£","¤","¥","¦","§","¨","©","ª","«","¬","®","¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾","¿","Æ","×","Ø","æ","÷","ø","");
    $str_replace2 = array("À","Á","Â","Ã","Ä","Å");
    $str_replace3 = array("È","É","Ê","Ë");
    $str_replace4 = array("Ì","Í","Î","Ï");
    $str_replace5 = array("Ò","Ó","Ô","Õ","Ö");
    $str_replace6 = array("Ù","Ú","Û","Ü");
    $str_replace7 = array("à","á","â","ã","ä","å");
    $str_replace8 = array("è","é","ê","ë");
    $str_replace9 = array("ì","í","î","ï","¡");
    $str_replace10 = array("ò","ó","ô","õ","ö","ð");
    $str_replace11 = array("ù","ú","û","ü");
    $str = str_replace($str_replace1,' ',$str);
    $str = str_replace($str_replace2,'A',$str);
    $str = str_replace($str_replace3,'E',$str);
    $str = str_replace($str_replace4,'I',$str);
    $str = str_replace($str_replace5,'O',$str);
    $str = str_replace($str_replace6,'U',$str);
    $str = str_replace($str_replace7,'a',$str);
    $str = str_replace($str_replace8,'e',$str);
    $str = str_replace($str_replace9,'i',$str);
    $str = str_replace($str_replace10,'o',$str);
    $str = str_replace($str_replace11,'u',$str);
    $str = str_replace('¢','c',$str);
    $str = str_replace('Ç','C',$str);
    $str = str_replace('Ð','D',$str);
    $str = str_replace('Ñ','N',$str);
    $str = str_replace('Ý','Y',$str);
    $str = str_replace('Þ','P',$str);
    $str = str_replace('ß','B',$str);
    $str = str_replace('ç','c',$str);
    $str = str_replace('ñ','n',$str);
    $str = str_replace('ý','y',$str);
    $str = str_replace('þ','p',$str);
    $str = str_replace('ÿ','y',$str);
    $str = str_replace('  ',' ',$str);
    return $str;
}

11. 过滤非英语字符,返回纯英文:

//过滤非英语字符串,返回纯英语
function toEnstr($inp) { 
    preg_replace('[^A-Za-z0-9_]', '', $inp);
    return $inp;
}

12.  替换mysql_real_escape_string和mysqli_real_escape_string
//替换mysql_real_escape_string和mysqli_real_escape_string
function mysql_escape_mimic($inp) { 
    if(is_array($inp)) 
        return array_map(__METHOD__, $inp); 
    if(!empty($inp) && is_string($inp)) { 
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp); 
    } 
    return $inp;
}

13. 下载(更简洁,封装更好)

    public function exportransplan(&$condition)
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $transportSer = D('Transportplan', 'Service');
        $data_arr = $transportSer->getTransportplan($param,$limit);
        $output = fopen('php://output', 'w') or die("can't open php://output");
        $filename = "filename" . date('Y-m-d', time());
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");
        ob_end_clean();
        $table_head = array(
            'title1', 'title2', 'title3', 'title4', 'title5', 'title6', 'title7', 'title8' );
        fputcsv($output, $table_head);
        foreach ($data_arr as $val) {
            fputcsv($output, array_values($val));
        }
        fclose($output) or die("can't close php://output");
        exit;
    }


待续~~~
PHP函数库,PHP函数大全,PHP函数实例,PHP函数手册,PHP5函数库实例 PHP函数库,PHP函数大全,PHP函数实例,PHP函数手册,PHP5函数库实例 curl获取远程文件内容 GD显示中文 PHP GIF动画生成类 PHP HTML转UBB函数 PHP XML转数组函数 PHP 缓存函数 PHP 设置COOKIE,并且加密COOKIE函数 PHP不缓存数据头 PHP伪造IP PHP全角半角转换函数 PHP农历函数 PHP分页函数 PHP判断字符串是否UTF8格式 php判断爬虫函数 PHP判断远程文件是否存在 PHP图片处理类:缩略,裁剪,圆角,倾斜 PHP多功能图片处理类 PHP多重判断删除文件函数 PHP实现英文标题的正确大写 PHP常用图片处理类 PHP常用测试函数 PHP得到当周每天日期 PHP文件下载类 PHP无限分类[左右值]算法 PHP显示日期、周几、农历初几、什么节日函数 PHP格式化数据,防止注入函数 PHP模拟登陆 PHP生成唯一标识符函数 PHP生成曲线图函数 PHP生成条形码 PHP统计字符串里单词出现次数 PHP缩略图类,可生成BMP格式 PHP自定义大小验证码函数 PHP获取.NET发出的WEBSERVICE数据 PHP获取FLV文件播放时间函数 PHP获取一年内所有周的开始和结束日期 php获取指定日期所在周的开始和结束日期 PHP读取文件前几个字节 判断文件类型函数 PHP连接ACCESS PHP采集程序中常用的函数 PHP随机产生指定长度中文字符串 SMTP类 url地址参数加密 一些常用验证函数 下拉-单选框选择 创建多级目录 删除数组中相同元素,只保留一个 判断路径是绝对目录还是相对目录 利用PHP搜索指定目录下指定的文件 加密解密 去掉指定的html标签 发送 trackback 数据包 图像处理类 图片验证码生成 字符集转换类 对要输入的字符串进行转换 对要输出的字符串进行反转换 对输入JS进行转换 寻找两个函数所有不同的元素 寻找两数组所有不同元素 得到文件类型 截取字符串中两个特定唯一字符之间的内容 截取指定长度字符串 折线图 按照比例改变图片大小(非生成缩略图) 收藏主页 数据验证类 数组转换成XML格式 日期计算 是否为电子邮件格式 柱形统计图 检查是否为一个合法的时间格式 检测URL地址有效性 检测文件是否图片 检测是否可以以网页形式显示 检测是否序列化后的字符串 模仿JAVASCRIPT的ESCAPE和UNESCAPE函数的功能 用curl函数读取远程文件 用file_getcontents提交数据 用php生成扭曲,有角度的验证图片(支持中文) 用正则加亮关键字 程序运行过程中直接输出 缩略图带版权信息函数 缩略图类 获得用户操作系统的换行符 获得用户的真实IP地址 计算字符串的长度(汉字按照两个字符计算) 设为主页 转换附件大小单位 转静态函数 遍历文件夹文件 采集网络数据 随机字符串 验证码 验证码类 验证输入的邮件地址是否合法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值