PHP

PHP一些常用的function(函数)整理

过滤四及以上字节的字符
function filterEmoji($str):string{
$str = preg_replace_callback('/./u', function(array $match){return strlen($match[0])>=4 ? '' : $match[0];}, $str);
return $str;
}
手机号码隐藏中间4位
function hideTel($tel):string{
return substr_replace($tel, '****', 4,4);
}
获取 文件后缀
function getSuffix($file):string{
return pathinfo($file,PATHINFO_EXTENSION);
}
获取客户端IP地址
/*
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param boolean $adv 是否进行高级模式获取(有可能被伪装)
* */
function getClientIp($type = 0, $adv = false) {
$type = $type ? 1 : 0;
static $ip = null;
if ($ip !== null){
return $ip[$type];
}
if ($adv) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos)
unset($arr[$pos]);
$ip = trim($arr[0]);
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
随机生成字符串
function createRandStr($length=8):string{
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
$randStr = '';
$strlength = strlen($str);
for ( $i = 0; $i < $length; $i++ ){
$randStr .= $str[ mt_rand(0, $strlength - 1) ];
}
return $randStr;
}
检测目录不存在或不是目录即创建目录
function checkPath($path):bool{
if(!file_exists($path) || !is_dir($path)){
return mkdir($path,0755,true);
}
return true;
}
检测上传文件是否合法
function isValid($filename,$isTest=true){
return $isTest ? is_file($filename) : is_uploaded_file($filename);
}
检测上传文件后缀
/*
* @param array|string $ext 允许后缀
* */
function checkExt($path,$ext):bool{
if(is_string($ext)){
$ext = explode(',',$ext);
}
$extension = strtolower(pathinfo($path,PATHINFO_EXTENSION));
return in_array($extension, $ext);
}
字符串截取 支持中文和其它编码
/*
* @param string $str
* @param int $start
* @param int $length
* @param string $charset
* @param bool $suffix
* */
function msubstr($str,$start=0,$length=0,$charset='utf-8',$suffix=false):string{
if(function_exists("mb_substr")){
$slice = mb_substr($str,$start,$length,$charset);
}elseif(function_exists('iconv_substr')){
$slice = iconv_substr($str,$start,$length,$charset);
}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;
}

 老铁们下班,今天先整理到这里了,后期再补充啦

0 个评论

要回复文章请先登录注册