字符串截取(从emlog提取,其实也就是substr的增强版)
function subString($strings, $start, $length){
if (function_exists('mb_substr') && function_exists('mb_strlen')) {
$sub_str = mb_substr($strings, $start, $length, 'utf8');
return mb_strlen($sub_str, 'utf8') < mb_strlen($strings, 'utf8') ? $sub_str . '...' : $sub_str;
}
$str = substr($strings, $start, $length);
$char = 0;
for ($i = 0; $i < strlen($str); $i++) { if (ord($str[$i]) >= 128)
$char++;
}
$str2 = substr($strings, $start, $length + 1);
$str3 = substr($strings, $start, $length + 2);
if ($char % 3 == 1) {
if ($length < = strlen($strings)) {
$str3 = $str3 .= '...';
}
return $str3;
}
if ($char % 3 == 2) {
if ($length <= strlen($strings)) {
$str2 = $str2 .= '...';
}
return $str2;
}
if ($char % 3 == 0) {
if ($length <= strlen($strings)) {
$str = $str .= '...';
}
return $str;
}
}
PHP字符串反转函数,支持中文、英文
function str_rev_gb($str){
//判断输入的是不是utf8类型的字符,否则退出
if(!is_string($str)||!mb_check_encoding($str,'UTF-8')){
exit("输入类型不是UTF8类型的字符串");
}
$array=array();
//将字符串存入数组
$l=mb_strlen($str,'UTF-8');
for($i=0;$i<$l;$i++){
$array[]=mb_substr($str,$i,1,'UTF-8');
}
//反转字符串
krsort($array);
//拼接字符串
$string=implode($array);
return $string;
}
$str1 = "Englist";
$str2 = "English中国";
$str3 = "Eng中lish国";
$str4 = "中华人民共和国";
echo $str1."->".str_rev_gb($str1)."<br>";
echo $str2."->".str_rev_gb($str2)."<br>";
echo $str3."->".str_rev_gb($str3)."<br>";
echo $str4."->".str_rev_gb($str4)."<br>";
注意:字符串的编码必须为utf-8的,如果程序的GBK的话,需要在使用的时候,先转一下编码。
获取客户端IP
/**
* 获取客户端IP
* @return [string] [description]
*/
function getClientIp(){
$ip = NULL;
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'];
}
// IP地址合法验证
$ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
return $ip;
}
版本二:
function GetIP(){
if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
else if (@$_SERVER["HTTP_CLIENT_IP"])
$ip = $_SERVER["HTTP_CLIENT_IP"];
else if (@$_SERVER["REMOTE_ADDR"])
$ip = $_SERVER["REMOTE_ADDR"];
else if (@getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (@getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if (@getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "Unknown";
return $ip;
}
// IP地址匿名化(最后一位替换为星号)
function AnonymousIP(){
$ip = GetIP();
if ($ip == "Unknown") {
$removed_ip = "未知用户";
}
if (strpos($ip, ":")) {
$removed_ip = "IPv6用户";
} else {
$reg1 = '/((?:\d+\.){3})\d+/';
$reg2 = '~(\d+)\.(\d+)\.(\d+)\.(\d+)~';
$removed_ip = preg_replace($reg1, "\\1*", $ip);
}
return $removed_ip;
}
获取在线IP
/**
* 获取在线IP
* @return String
*/
function getOnlineIp($format=0) {
global $S_GLOBAL;
if(empty($S_GLOBAL['onlineip'])) {
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$S_GLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
if($format) {
$ips = explode('.', $S_GLOBAL['onlineip']);
for($i=0;$i<3;$i++) {
$ips[$i] = intval($ips[$i]);
}
return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
} else {
return $S_GLOBAL['onlineip'];
}
}
获取url
/**
* 获取url
* @return [type] [description]
*/
function getUrl(){
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
字符串加密(支持中文)
function dencrypt($string, $isEncrypt = true, $key = "youdian"){
if (!isset($string{0}) || !isset($key{0})) {
return false;
}
$dynKey = $isEncrypt ? hash('sha1', microtime(true)) : substr($string, 0, 40);
$fixedKey = hash('sha1', $key);
$dynKeyPart1 = substr($dynKey, 0, 20);
$dynKeyPart2 = substr($dynKey, 20);
$fixedKeyPart1 = substr($fixedKey, 0, 20);
$fixedKeyPart2 = substr($fixedKey, 20);
$key = hash('sha1', $dynKeyPart1 . $fixedKeyPart1 . $dynKeyPart2 . $fixedKeyPart2);
$string = $isEncrypt ? $fixedKeyPart1 . $string . $dynKeyPart2 : (isset($string{339}) ? gzuncompress(base64_decode(substr($string, 40))) : base64_decode(substr($string, 40)));
$n = 0;
$result = '';
$len = strlen($string);
for ($n = 0; $n < $len; $n++) {
$result .= chr(ord($string{$n}) ^ ord($key{$n % 40}));
}
return $isEncrypt ? $dynKey . str_replace('=', '', base64_encode($n > 299 ? gzcompress($result) : $result)) : substr($result, 20, -20);
}
获取当前站点的访问路径根目录
/**
* 获取当前站点的访问路径根目录
* @return [type] [description]
*/
function getSiteUrl() {
$uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
return 'http://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/')+1);
}
检查字符串是否包含中文
function CheckChinese($string){
if (preg_match("/[\x7f-\xff]/", $string)) {
return true;
} else {
return false;
}
}
生成随机字符串,自定义长度
function CreateRandomString($length){
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = "";
for ($i = 0; $i < $length; $i++) {
$password .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $password;
}
php获取文件扩展名函数
$file = "/home/allen/backup_20150520.txt";
for($i=1; $i < 6; $i++) {
$func = 'get_file_ext_' . $i;
var_dump($func($file));
}
function get_file_ext_1($file) {
return strtolower(trim(substr(strrchr($file, '.'), 1)));
}
function get_file_ext_2($file) {
return strtolower(trim(pathinfo($file, PATHINFO_EXTENSION)));
}
function get_file_ext_3($file) {
return strtolower(trim(substr($file, strrpos($file, '.')+1)));
}
function get_file_ext_4($file) {
return strtolower(trim(array_pop(explode('.', $file))));
}
function get_file_ext_5($file) {
$tok = strtok($file, '.');
while($tok !== false) {
$return = $tok;
$tok = strtok('.');
}
return strtolower(trim($return));
}
调用函数:
echo get_file_ext_1($file); // txt
扩展:一些php项目中比较通用的php函数分享