首页 > 代码库 > php常考功能函数
php常考功能函数
1.统计数组元素个数
$arr = array( ‘1011,1003,1008,1001,1000,1004,1012‘, ‘1009‘, ‘1011,1003,1111‘ );$result = array();foreach ($arr as $str) { $str_arr = explode(‘,‘, $str); foreach ($str_arr as $v) { // $result[$v] = isset($result[$v]) ? $result[$v] : 0; // $result[$v] = $result[$v] + 1; $result[$v] = isset($result[$v]) ? $result[$v]+1 : 1; }}print_r($result);//Array([1011] => 2[1003] => 2[1008] => 1[1001] => 1[1000] => 1[1004] => 1[1012] => 1[1009] => 1[1111] => 1)
2. 循环删除目录
function cleanup_directory($dir) { foreach (new DirectoryIterator($dir) as $file) { if ($file->isDir()) { if (! $file->isDot()) { cleanup_directory($file->getPathname()); } } else { unlink($file->getPathname()); } } rmdir($dir);}
3.无限极分类生成树
function generateTree($items){ $tree = array(); foreach($items as $item){ if(isset($items[$item[‘pid‘]])){ $items[$item[‘pid‘]][‘son‘][] = &$items[$item[‘id‘]]; }else{ $tree[] = &$items[$item[‘id‘]]; } } return $tree;}function generateTree2($items){ foreach($items as $item) $items[$item[‘pid‘]][‘son‘][$item[‘id‘]] = &$items[$item[‘id‘]]; return isset($items[0][‘son‘]) ? $items[0][‘son‘] : array();} $items = array( 1 => array(‘id‘ => 1, ‘pid‘ => 0, ‘name‘ => ‘安徽省‘), 2 => array(‘id‘ => 2, ‘pid‘ => 0, ‘name‘ => ‘浙江省‘), 3 => array(‘id‘ => 3, ‘pid‘ => 1, ‘name‘ => ‘合肥市‘), 4 => array(‘id‘ => 4, ‘pid‘ => 3, ‘name‘ => ‘长丰县‘), 5 => array(‘id‘ => 5, ‘pid‘ => 1, ‘name‘ => ‘安庆市‘),);print_r(generateTree($items));/** * 如何取数据格式化的树形数据 */$tree = generateTree($items);function getTreeData($tree){ foreach($tree as $t){ echo $t[‘name‘].‘<br>‘; if(isset($t[‘son‘])){ getTreeData($t[‘son‘]); } }}
4.数组排序 a - b 是数字数组写法 遇到字符串的时候就要
1 var test = [‘ab‘, ‘ac‘, ‘bd‘, ‘bc‘]; 2 test.sort(function(a, b) { 3 if(a < b) { 4 return -1; 5 } 6 7 if(a > b) { 8 return 1; 9 }10 11 return 0;12 });
5.array_reduce
$raw = [1,2,3,4,5,];// array_reduce 的第三个参数是 $result 的初始值array_reduce($raw, function($result, $value) { $result[$value] = $value; return $result;}, []);// [1 => 1, 2 => 2, ... 5 => 5]
6.array_map 闭包中只接受一个或者多个参数,闭包的参数数量和 array_map 本身的参数数量必须一致
$input = [‘key‘ => ‘value‘];array_map(function($key, $value) { echo $key . $value;}, array_keys($input), $input)// ‘keyvalue‘$double = function($item) { return 2 * $item;} $result = array_map($double, [1,2,3]); // 2 4 6
7.繁殖兔子
$month = 12; $fab = array(); $fab[0] = 1; $fab[1] = 1; for ($i = 2; $i < $month; $i++) { $fab[$i] = $fab[$i - 1] + $fab[$i - 2]; } for ($i = 0; $i < $month; $i++) { echo sprintf("第{%d}个月兔子为:{%d}",$i, $fab[$i])."<br/>"; }
8 .datetime
function getCurMonthFirstDay($date){ return date(‘Y-m-01‘, strtotime($date));} getCurMonthLastDay(‘2015-07-23‘)function getCurMonthLastDay($date){ return date(‘Y-m-d‘, strtotime(date(‘Y-m-01‘, strtotime($date)) . ‘ +1 month -1 day‘));}
9.加密解密
function encrypt($data, $key){ $key = md5($key); $x = 0; $len = strlen($data); $l = strlen($key); $char = ‘‘; for ($i = 0; $i < $len; $i++) { if ($x == $l) { $x = 0; } $char .= $key{$x}; $x++; } $str = ‘‘; for ($i = 0; $i < $len; $i++) { $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256); } return base64_encode($str);} function decrypt($data, $key){ $key = md5($key); $x = 0; $data = base64_decode($data); $len = strlen($data); $l = strlen($key); $char = ‘‘; for ($i = 0; $i < $len; $i++) { if ($x == $l) { $x = 0; } $char .= substr($key, $x, 1); $x++; } $str = ‘‘; for ($i = 0; $i < $len; $i++) { if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) { $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1))); } else { $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1))); } } return $str;}
10 . 多维数组降级
function array_flatten($arr) { $result = []; array_walk_recursive($arr, function($value) use (&$result) { $result[] = $value; }); return $result;}print_r(array_flatten([1,[2,3],[4,5]]));// [1,[2,3],[4,5]] => [1,2,3,4,5]// var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])var test = [1,2,3,[4,5,6],[7,8]];[].concat.apply([], test); // [1,2,3,4,5,6,7,8] 对于 test 数组中的每一个 value, 将它 concat 到空数组 [] 中去,而因为 concat 是 Array 的 prototype,所以我们用一个空 array 作载体var test1 = [1,2,[3,[4,[5]]]]; function flatten(arr) { return arr.reduce(function(pre, cur) { if(Array.isArray(cur)) { return flatten(pre.concat(cur)); } return pre.concat(cur); }, []);} // [1,2,3,4,5]json_encode中文function json_encode_wrapper ($result){ if(defined(‘JSON_UNESCAPED_UNICODE‘)){ return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK); }else { return preg_replace( array("#\\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie", "/\"(\d+)\"/",), array("iconv(‘UCS-2‘, ‘UTF-8‘, pack(‘H4‘, ‘\\1‘))", "\\1"), json_encode($result) ); }}
12.二维数组去重
$arr = array( array(‘id‘=>‘2‘,‘title‘=>‘...‘,‘ding‘=>‘1‘,‘jing‘=>‘1‘,‘time‘=>‘...‘,‘url‘=>‘...‘,‘dj‘=>‘...‘), array(‘id‘=>‘2‘,‘title‘=>‘...‘,‘ding‘=>‘1‘,‘jing‘=>‘1‘,‘time‘=>‘...‘,‘url‘=>‘...‘,‘dj‘=>‘...‘) );function about_unique($arr=array()){ /*将该种二维数组看成一维数组,则 该一维数组的value值有相同的则干掉只留一个,并将该一维 数组用重排后的索引数组返回,而返回的一维数组中的每个元素都是 原始key值形成的关联数组 */ $keys =array(); $temp = array(); foreach($arr[0] as $k=>$arrays) { /*数组记录下关联数组的key值*/ $keys[] = $k; } //return $keys; /*降维*/ foreach($arr as $k=>$v) { $v = join(",",$v); //降维 $temp[] = $v; } $temp = array_unique($temp); //去掉重复的内容 foreach ($temp as $k => $v){ /*再将拆开的数组按索引数组重新组装*/ $temp[$k] = explode(",",$v); } //return $temp; /*再将拆开的数组按关联数组key值重新组装*/ foreach($temp as $k=>$v) { foreach($v as $kkk=>$ck) { $data[$k][$keys[$kkk]] = $temp[$k][$kkk]; } } return $data; }
13.格式化字节大小
/*** 格式化字节大小* @param number $size 字节数* @param string $delimiter 数字和单位分隔符* @return string 格式化后的带单位的大小* @author */function format_bytes($size, $delimiter = ‘‘) { $units = array(‘B‘, ‘KB‘, ‘MB‘, ‘GB‘, ‘TB‘, ‘PB‘); for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i];}
14.3分钟前
/*** 将指定时间戳转换为截止当前的xx时间前的格式 例如 return ‘3分钟前‘‘* @param string|int $timestamp unix时间戳* @return string*/function time_ago($timestamp) { $etime = time() - $timestamp; if ($etime < 1) return ‘刚刚‘; $interval = array ( 12 * 30 * 24 * 60 * 60 => ‘年前 (‘.date(‘Y-m-d‘, $timestamp).‘)‘, 30 * 24 * 60 * 60 => ‘个月前 (‘.date(‘m-d‘, $timestamp).‘)‘, 7 * 24 * 60 * 60 => ‘周前 (‘.date(‘m-d‘, $timestamp).‘)‘, 24 * 60 * 60 => ‘天前‘, 60 * 60 => ‘小时前‘, 60 => ‘分钟前‘, 1 => ‘秒前‘ ); foreach ($interval as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); return $r . $str; } };}
15.身份证号
/*** 判断参数字符串是否为天朝身份证号* @param $id 需要被判断的字符串或数字* @return mixed false 或 array[有内容的array boolean为真]*/function is_citizen_id($id) { //长度效验 18位身份证中的X为大写 $id = strtoupper($id); if(!(preg_match(‘/^\d{17}(\d|X)$/‘,$id) || preg_match(‘/^\d{15}$/‘,$id))) { return false; } //15位老号码转换为18位 并转换成字符串 $Wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); $Ai = array(‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘); $cardNoSum = 0; if(strlen($id)==16) { $id = substr(0, 6).‘19‘.substr(6, 9); for($i = 0; $i < 17; $i++) { $cardNoSum += substr($id,$i,1) * $Wi[$i]; } $seq = $cardNoSum % 11; $id = $id.$Ai[$seq]; } //效验18位身份证最后一位字符的合法性 $cardNoSum = 0; $id17 = substr($id,0,17); $lastString = substr($id,17,1); for($i = 0; $i < 17; $i++) { $cardNoSum += substr($id,$i,1) * $Wi[$i]; } $seq = $cardNoSum % 11; $realString = $Ai[$seq]; if($lastString!=$realString) {return false;} //地域效验 $oCity = array(11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外"); $City = substr($id, 0, 2); $BirthYear = substr($id, 6, 4); $BirthMonth = substr($id, 10, 2); $BirthDay = substr($id, 12, 2); $Sex = substr($id, 16,1) % 2 ;//男1 女0 //$Sexcn = $Sex?‘男‘:‘女‘; //地域验证 if(is_null($oCity[$City])) {return false;} //出生日期效验 if($BirthYear>2078 || $BirthYear<1900) {return false;} $RealDate = strtotime($BirthYear.‘-‘.$BirthMonth.‘-‘.$BirthDay); if(date(‘Y‘,$RealDate)!=$BirthYear || date(‘m‘,$RealDate)!=$BirthMonth || date(‘d‘,$RealDate)!=$BirthDay) { return false; } return array(‘id‘=>$id,‘location‘=>$oCity[$City],‘Y‘=>$BirthYear,‘m‘=>$BirthMonth,‘d‘=>$BirthDay,‘sex‘=>$Sex);}
16.获取二维数组中某个key的集合
$user = array( 0 => array( ‘id‘ => 1, ‘name‘ => ‘张三‘, ‘email‘ => ‘zhangsan@sina.com‘, ), 1 => array( ‘id‘ => 2, ‘name‘ => ‘李四‘, ‘email‘ => ‘lisi@163.com‘, ), 2 => array( ‘id‘ => 5, ‘name‘ => ‘王五‘, ‘email‘ => ‘10000@qq.com‘, ), ...... );$ids = array(); $ids = array_map(‘array_shift‘, $user);$ids = array_column($user, ‘id‘);//php5.5$names = array(); $names = array_reduce($user, create_function(‘$v,$w‘, ‘$v[$w["id"]]=$w["name"];return $v;‘));
1、PHP加密解密
PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。
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‘, ‘jb51欢迎您‘,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; }
使用方法如下:
echo generateRandomString(20);
3、PHP获取文件扩展名(后缀)
以下函数可以快速获取文件的扩展名即后缀。
function getExtension($filename){ $myext = substr($filename, strrpos($filename, ‘.‘)); return str_replace(‘.‘,‘‘,$myext); }
使用方法如下:
$filename = ‘我的文档.doc‘; echo getExtension($filename);
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‘); echo formatSize($thefile);
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
以下函数可以获取当前页面的URL,不管是http还是https。
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强制下载文件
有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。
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,以下代码可以获取客户端真实的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、PHP防止SQL注入
我们在查询数据库时,出于安全考虑,需要过滤一些非法字符防止SQL恶意注入,请看一下函数:
function injCheck($sql_str) { $check = preg_match(‘/select|insert|update|delete|\‘|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/‘, $sql_str); if ($check) { echo ‘非法字符!!‘; exit; } else { return $sql_str; } }
使用方法如下:echo injCheck(‘1 or 1=1‘);
12、PHP页面提示与跳转
我们在进行表单操作时,有时为了友好需要提示用户操作结果,并跳转到相关页面,请看以下函数:
function message($msgTitle,$message,$jumpUrl){ $str = ‘<!DOCTYPE HTML>‘; $str .= ‘<html>‘; $str .= ‘<head>‘; $str .= ‘<meta charset="utf-8">‘; $str .= ‘<title>页面提示</title>‘; $str .= ‘<style type="text/css">‘; $str .= ‘*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial, sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}‘; $str .= ‘</style>‘; $str .= ‘</head>‘; $str .= ‘<body>‘; $str .= ‘<div>‘; $str .= ‘<h3>‘.$msgTitle.‘</h3>‘; $str .= ‘<div>‘; $str .= ‘<h4>‘.$message.‘</h4>‘; $str .= ‘<p>系统将在 <span style="color:blue;font-weight:bold">3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="http://www.mamicode.com/{$jumpUrl}">这里</a> 跳转</p>‘; $str .= "<script>setTimeout(‘location.replace(\‘".$jumpUrl."\‘)‘,2000)</script>"; $str .= ‘</div>‘; $str .= ‘</div>‘; $str .= ‘</body>‘; $str .= ‘</html>‘; echo $str; }
使用方法如下:message(‘操作提示‘,‘操作成功!‘,‘http://www.taoip.cn‘);
13、PHP计算时长
我们在处理时间时,需要计算当前时间距离某个时间点的时长,如计算客户端运行时长,通常用hh:mm:ss表示。
function changeTimeType($seconds) { if ($seconds > 3600) { $hours = intval($seconds / 3600); $minutes = $seconds % 3600; $time = $hours . ":" . gmstrftime(‘%M:%S‘, $minutes); } else { $time = gmstrftime(‘%H:%M:%S‘, $seconds); } return $time; }
使用方法如下:$seconds = 3712; echo changeTimeType($seconds);
php常考功能函数