平时工作需要经常需要用到一些函数,其实可以很好的封装,但发现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;
}
待续~~~