从thinksaas中取的PHP常用处理函数.php
//处理时间的函数
function getTime($btime, $etime){
if ($btime < $etime) {
$stime = $btime;
$endtime = $etime;
}else {
$stime = $etime;
$endtime = $btime;
}
$timec = $endtime - $stime;
$days = intval($timec / 86400);
$rtime = $timec % 86400;
$hours = intval($rtime / 3600);
$rtime = $rtime % 3600;
$mins = intval($rtime / 60);
$secs = $rtime % 60;
if($days>=1){
return $days.' 天前';
}
if($hours>=1){
return $hours.' 小时前';
}
if($mins>=1){
return $mins.' 分钟前';
}
if($secs>=1){
return $secs.' 秒前';
}
}
//获取用户IP
function getIp(){
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
$PHP_IP = getenv('HTTP_CLIENT_IP');
}elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
$PHP_IP = getenv('HTTP_X_FORWARDED_FOR');
}elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
$PHP_IP = getenv('REMOTE_ADDR');
}elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
$PHP_IP = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $PHP_IP, $ipmatches);
$PHP_IP = $ipmatches[0] ? $ipmatches[0] : 'unknown';
return $PHP_IP;
}
//纯文本输入
function t($text){
$text=preg_replace('/\[.*?\]/is','',$text);
$text = cleanJs ( $text );
//彻底过滤空格BY QINIAO
$text = preg_replace('/\s(?=\s)/', '', $text);
$text = preg_replace('/[\n\r\t]/', ' ', $text);
$text = str_replace ( ' ', ' ', $text );
$text = str_replace ( ' ', '', $text );
$text = str_replace ( ' ', '', $text );
$text = str_replace ( '&', '', $text );
$text = str_replace ( '=', '', $text );
$text = str_replace ( '-', '', $text );
$text = str_replace ( '#', '', $text );
$text = str_replace ( '%', '', $text );
$text = str_replace ( '!', '', $text );
$text = str_replace ( '@', '', $text );
$text = str_replace ( '^', '', $text );
$text = str_replace ( '*', '', $text );
$text = str_replace ( 'amp;', '', $text );
$text = str_replace ( 'position', '', $text );
$text = strip_tags ( $text );
$text = htmlspecialchars ( $text );
$text = str_replace ( "'", "", $text );
return $text;
}
//输入安全的html,针对存入数据库中的数据进行的过滤和转义
function h($text){
$text = trim ( $text );
$text = htmlspecialchars ( $text );
$text = addslashes ( $text );
return $text;
}
//utf-8截取
function cututf8($string, $start = 0,$sublen,$append=true){
$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 && $append==true){
return join('', array_slice($t_string[0], $start, $sublen))."...";
}else{
return join('', array_slice($t_string[0], $start, $sublen));
}
}