收藏几个PHP助手函数

1, 获取客户端IP地址:

/**
 * 获取客户端的IP地址
 * 
 * @since 1.0.0
 * @return string $ip
 */
function getClientIP() {
	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);
}

2,判断传入字符串是否为邮箱

/**
 * 判断传入字符串是否为邮箱
 * 
 * @since 1.0.0
 * @param String $email
 * @return boolean
 */
function isEmail($email){
	return (ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",$email));
}

3,产生给定长度的随机字符串

/**
 * 产生给定长度的随机字符串
 * 
 * @since 1.0.0
 * @param Number $length
 * @return String $hash
 */
function randomStr($length = 32) {
	$hash = '';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$max = strlen ( $chars ) - 1;
	mt_srand ( ( double ) microtime () * 1000000 );
	for($i = 0; $i < $length; $i ++) {
		$hash .= $chars [mt_rand ( 0, $max )];
	}
	return $hash;
}

4,截取字符串函数,支持截取指定长度的汉字字符

/**
 * 截取字符串函数,支持截取指定长度的汉字字符
 * 
 * @since 1.0.0
 * @param $str
 * @param $from
 * @param $len
 * @return string $str
 */
function utf8CutStr($str, $from, $len) {
	$curlen = strlen($str);
	if($curlen>$len){
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s','$1',$str).'...'; 
	}else{
		return $str;
	}
}

后续整理,持续增加...

这篇文章目前有1条评论

  1. 小D 2011-10-19 15:17

    唉…!!PHP的白痴路过!~~~~虽然能看懂..但写不出!哈哈!!!!!!!

    沙发王 !
Leave a Reply

(必填项)

(必填项)

(可选)