您好,欢迎访问一九零五行业门户网

php 常用函数收藏(一)_PHP教程

/**
  * 返回经addslashes处理过的字符串或数组
  * @param $string 需要处理的字符串或数组
  * @return mixed
  */
 function new_addslashes($string){
     if(!is_array($string)) return addslashes($string);
     foreach($string as $key => $val) $string[$key] = new_addslashes($val);
     return $string;
 }
/**
  * 返回经stripslashes处理过的字符串或数组
  * @param $string 需要处理的字符串或数组
  * @return mixed
  */
 function new_stripslashes($string) {
     if(!is_array($string)) return stripslashes($string);
     foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
     return $string;
 }
/**
  * 返回经addslashe处理过的字符串或数组
  * @param $obj 需要处理的字符串或数组www.2cto.com
  * @return mixed
  */
 function new_html_special_chars($string) {
     if(!is_array($string)) return htmlspecialchars($string);
     foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
     return $string;
 }
 /**
  * 安全过滤函数
  *
  * @param $string
  * @return string
  */
 function safe_replace($string) {
     $string = str_replace('%20','',$string);
     $string = str_replace('%27','',$string);
     $string = str_replace('%2527','',$string);
     $string = str_replace('*','',$string);
     $string = str_replace('','',$string);
     $string = str_replace(','',$string);
     $string = str_replace('','',$string);
     $string = str_replace(';','',$string);
     $string = str_replace('     $string = str_replace('>','>',$string);
     $string = str_replace({,'',$string);
     $string = str_replace('}','',$string);
     return $string;
 }
/**
  * 过滤ascii码从0-28的控制字符
  * @return string
  */
 function trim_unsafe_control_chars($str) {
     $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
     return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
 }
/**
  * 格式化文本域内容
  *
  * @param $string 文本域内容
  * @return string
  */
 function trim_textarea($string) {
     $string = nl2br ( str_replace ( ' ', ' ', $string ) );
     return $string;
 }
/**
  * 将文本格式成适合js输出的字符串
  * @param string $string 需要处理的字符串
  * @param intval $isjs 是否执行字符串格式化,默认为执行
  * @return string 处理后的字符串
  */
 function format_js($string, $isjs = 1)
 {
     $string = addslashes(str_replace(array(\r, \n), array('', ''), $string));
     return $isjs ? 'document.write('.$string.');' : $string;
 }
/**
  * 转义javascript 代码标记
  *
  * @param $str
  * @return mixed
  */
 function trim_script($str) {
     $str = preg_replace ( '/\]*?)\>/si', '', $str );
     $str = preg_replace ( '/\]*?)\>/si', '', $str );
     $str = preg_replace ( '/\]*?)\>/si', '', $str );
     $str = preg_replace ( '/]]\>/si', ']] >', $str );
     return $str;
 }
 /**
  * 获取当前页面完整url地址
  */
 function get_url() {
     $sys_protocal = isset($_server['server_port']) && $_server['server_port'] == '443' ? 'https://' : 'http://';
     $php_self = $_server['php_self'] ? safe_replace($_server['php_self']) : safe_replace($_server['script_name']);
     $path_info = isset($_server['path_info']) ? safe_replace($_server['path_info']) : '';
     $relate_url = isset($_server['request_uri']) ? safe_replace($_server['request_uri']) : $php_self.(isset($_server['query_string']) ? '?'.safe_replace($_server['query_string']) : $path_info);
     return $sys_protocal.(isset($_server['http_host']) ? $_server['http_host'] : '').$relate_url;
 }
 /**
  * 字符截取 支持utf8/gbk
  * @param $string
  * @param $length
  * @param $dot
  */
 function str_cut($string, $length, $dot = '...') {
     $strlen = strlen($string);
     if($strlen      $string = str_replace(array(' ',' ', '&', '', ''', '“', '”', '—', '', '·', '…'), array('∵',' ', '&', '', ', '“', '”', '—', '', '·', '…'), $string);
     $strcut = '';
     if(strtolower(charset) == 'utf-8') {
         $length = intval($length-strlen($dot)-$length/3);
         $n = $tn = $noc = 0;
         while($n              $t = ord($string[$n]);
             if($t == 9 || $t == 10 || (32                  $tn = 1; $n++; $noc++;
             } elseif(194                  $tn = 2; $n += 2; $noc += 2;
             } elseif(224                  $tn = 3; $n += 3; $noc += 2;
             } elseif(240                  $tn = 4; $n += 4; $noc += 2;
             } elseif(248                  $tn = 5; $n += 5; $noc += 2;
             } elseif($t == 252 || $t == 253) {
                 $tn = 6; $n += 6; $noc += 2;
             } else {
                 $n++;
             }
             if($noc >= $length) {
                 break;
             }
         }
         if($noc > $length) {
             $n -= $tn;
         }
         $strcut = substr($string, 0, $n);
         $strcut = str_replace(array('∵', '&', '', ', '“', '”', '—', '', '·', '…'), array(' ', '&', '', ''', '“', '”', '—', '', '·', '…'), $strcut);
     } else {
         $dotlen = strlen($dot);
         $maxi = $length - $dotlen - 1;
         $current_str = '';
         $search_arr = array('&',' ', '', ', '“', '”', '—', '', '·', '…','∵');
         $replace_arr = array('&',' ', '', ''', '“', '”', '—', '', '·', '…',' ');
         $search_flip = array_flip($search_arr);
         for ($i = 0; $i              $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
             if (in_array($current_str, $search_arr)) {
                 $key = $search_flip[$current_str];
                 $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
             }
             $strcut .= $current_str;
         }
     }
     return $strcut.$dot;
 }
/**
  * 获取请求ip
  *
  * @return ip地址
  */
 function ip() {
     if(getenv('http_client_ip') && strcasecmp(getenv('http_client_ip'), 'unknown')) {
         $ip = getenv('http_client_ip');
     } elseif(getenv('http_x_forwarded_for') && strcasecmp(getenv('http_x_forwarded_for'), 'unknown')) {
         $ip = getenv('http_x_forwarded_for');
     } elseif(getenv('remote_addr') && strcasecmp(getenv('remote_addr'), 'unknown')) {
         $ip = getenv('remote_addr');
     } elseif(isset($_server['remote_addr']) && $_server['remote_addr'] && strcasecmp($_server['remote_addr'], 'unknown')) {
         $ip = $_server['remote_addr'];
     }
     return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
 }
function get_cost_time() {
     $microtime = microtime ( true );
     return $microtime - sys_start_time;
 }
 /**
  * 程序执行时间
  *
  * @return  int 单位ms
  */
 function execute_time() {
     $stime = explode ( ' ', sys_start_time );
     $etime = explode ( ' ', microtime () );
     return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
 }
/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ,默认为0123456789
 * @return   string     字符串
 */
 function random($length, $chars = '0123456789') {
     $hash = '';
     $max = strlen($chars) - 1;
     for($i = 0; $i          $hash .= $chars[mt_rand(0, $max)];
     }
     return $hash;
 }
/**
 * 将字符串转换为数组
 *
 * @param    string  $data   字符串
 * @return   array   返回数组格式,如果,data为空,则返回空数组
 */
 function string2array($data) {
     if($data == '') return array();
     eval(\$array = $data;);
     return $array;
 }
 /**
 * 将数组转换为字符串
 *
 * @param    array   $data       数组
 * @param    bool    $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
 * @return   string  返回字符串,如果,data为空,则返回空
 */
 function array2string($data, $isformdata = 1) {
     if($data == '') return '';
     if($isformdata) $data = new_stripslashes($data);
     return addslashes(var_export($data, true));
 }
/**
 * 转换字节数为其他单位
 *
 *
 * @param    string  $filesize   字节大小
 * @return   string  返回大小
 */
 function sizecount($filesize) {
     if ($filesize >= 1073741824) {
         $filesize = round($filesize / 1073741824 * 100) / 100 .' gb';
     } elseif ($filesize >= 1048576) {
         $filesize = round($filesize / 1048576 * 100) / 100 .' mb';
     } elseif($filesize >= 1024) {
         $filesize = round($filesize / 1024 * 100) / 100 . ' kb';
     } else {
         $filesize = $filesize.' bytes';
     }
     return $filesize;
 }
 /**
 * 字符串加密、解密函数
 *
 *
 * @param    string  $txt        字符串
 * @param    string  $operation  encode为加密,decode为解密,可选参数,默认为encode,
 * @param    string  $key        密钥:数字、字母、下划线
 * @return   string
 */
 function sys_auth($txt, $operation = 'encode', $key = '') {
     $key    = $key ? $key : pc_base::load_config('system', 'auth_key');
     $txt    = $operation == 'encode' ? (string)$txt : base64_decode($txt);
     $len    = strlen($key);
     $code   = '';
     for($i=0; $i         $k      = $i % $len;
         $code  .= $txt[$i] ^ $key[$k];
     }
     $code = $operation == 'decode' ? $code : base64_encode($code);
     return $code;
 }
/**
 * 语言文件处理
 *
 * @param    string      $language   标示符
 * @param    array       $pars   转义的数组,二维数组,'key1'=>'value1','key2'=>'value2',
 * @param    string      $modules 多个模块之间用半角逗号隔开,如:member,guestbook
 * @return   string      语言字符
 */
 function l($language = 'no_language',$pars = array(), $modules = '') {
     static $lang = array();
     static $lang_modules = array();
     static $lang = '';
     if(defined('in_admin')) {
         $lang = sys_style ? sys_style : 'zh-cn';
     } else {
         $lang = pc_base::load_config('system','lang');
     }
     if(!$lang) {
         require_once pc_path.'languages'.directory_separator.$lang.directory_separator.'system.lang.php';
         if(defined('in_admin')) require_once pc_path.'languages'.directory_separator.$lang.directory_separator.'system_menu.lang.php';
         if(file_exists(pc_path.'languages'.directory_separator.$lang.directory_separator.route_m.'.lang.php')) require pc_path.'languages'.directory_separator.$lang.directory_separator.route_m.'.lang.php';
     }
     if(!emptyempty($modules)) {
         $modules = explode(',',$modules);
         foreach($modules as $m) {
             if(!isset($lang_modules[$m])) require pc_path.'languages'.directory_separator.$lang.directory_separator.$m.'.lang.php';
         }
     }
     if(!array_key_exists($language,$lang)) {
         return $lang['no_language'].'['.$language.']';
     } else {
         $language = $lang[$language];
         if($pars) {
             foreach($pars as $_k=>$_v) {
                 $language = str_replace('{'.$_k.'}',$_v,$language);
             }
         }
         return $language;
     }
 }
/**
  * 模板调用
  *
  * @param $module
  * @param $template
  * @param $istag
  * @return unknown_type
  */
 function template($module = 'content', $template = 'index', $style = '') {
if(strpos($module, 'plugin/')!== false) {
         $plugin = str_replace('plugin/', '', $module);
         return p_template($plugin, $template,$style);
     }
     $module = str_replace('/', directory_separator, $module);
     if(!emptyempty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
     } elseif (emptyempty($style) && !defined('style')) {
         if(defined('siteid')) {
             $siteid = siteid;
         } else {
             $siteid = param::get_cookie('siteid');
         }
         if (!$siteid) $siteid = 1;
         $sitelist = getcache('sitelist','commons');
         if(!emptyempty($siteid)) {
             $style = $sitelist[$siteid]['default_style'];
         }
     } elseif (emptyempty($style) && defined('style')) {
         $style = style;
     } else {
         $style = 'default';
     }
     if(!$style) $style = 'default';
     $template_cache = pc_base::load_sys_class('template_cache');
     $compiledtplfile = phpcms_path.'caches'.directory_separator.'caches_template'.directory_separator.$style.directory_separator.$module.directory_separator.$template.'.php';
     if(file_exists(pc_path.'templates'.directory_separator.$style.directory_separator.$module.directory_separator.$template.'.html')) {
         if(!file_exists($compiledtplfile) || (@filemtime(pc_path.'templates'.directory_separator.$style.directory_separator.$module.directory_separator.$template.'.html') > @filemtime($compiledtplfile))) {    
             $template_cache->template_compile($module, $template, $style);
         }
     } else {
         $compiledtplfile = phpcms_path.'caches'.directory_separator.'caches_template'.directory_separator.'default'.directory_separator.$module.directory_separator.$template.'.php';
         if(!file_exists($compiledtplfile) || (file_exists(pc_path.'templates'.directory_separator.'default'.directory_separator.$module.directory_separator.$template.'.html') && filemtime(pc_path.'templates'.directory_separator.'default'.directory_separator.$module.directory_separator.$template.'.html') > filemtime($compiledtplfile))) {
             $template_cache->template_compile($module, $template, 'default');
         } elseif (!file_exists(pc_path.'templates'.directory_separator.'default'.directory_separator.$module.directory_separator.$template.'.html')) {
             showmessage('template does not exist.'.directory_separator.$style.directory_separator.$module.directory_separator.$template.'.html');
         }
     }
     return $compiledtplfile;
 }
/**
  * 输出自定义错误
  *
  * @param $errno 错误号
  * @param $errstr 错误描述
  * @param $errfile 报错文件地址
  * @param $errline 错误行号
  * @return string 错误提示
  */
function my_error_handler($errno, $errstr, $errfile, $errline) {
     if($errno==8) return '';
     $errfile = str_replace(phpcms_path,'',$errfile);
     if(pc_base::load_config('system','errorlog')) {
         error_log(''.date('m-d h:i:s',sys_time).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline.\r\n, 3, cache_path.'error_log.php');
     } else {
         $str = '
errorno:' . $errno . ',str:' . $errstr . ',file:' . $errfile . ',line' . $errline .'
need help?
';
         echo $str;
     }
 }
/**
  * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
  * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
  * @param string $msg 提示信息
  * @param mixed(string/array) $url_forward 跳转地址
  * @param int $ms 跳转等待时间
  */
 function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
     if(defined('in_admin')) {
         include(admin::admin_tpl('showmessage', 'admin'));
     } else {
         include(template('content', 'message'));
     }
     exit;
 }
 /**
  * 查询字符是否存在于某字符串
  *
  * @param $haystack 字符串
  * @param $needle 要查找的字符
  * @return bool
  */
 function str_exists($haystack, $needle)
 {
     return !(strpos($haystack, $needle) === false);
 }
/**
  * 取得文件扩展
  *
  * @param $filename 文件名
  * @return 扩展名
  */
 function fileext($filename) {
     return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
 }
/**
  * 加载模板标签缓存
  * @param string $name 缓存名
  * @param integer $times 缓存时间
  */
 function tpl_cache($name,$times = 0) {
     $filepath = 'tpl_data';
     $info = getcacheinfo($name, $filepath);
     if (sys_time - $info['filemtime'] >= $times) {
         return false;
     } else {
         return getcache($name,$filepath);
     }
 }
/**
  * 写入缓存,默认为文件缓存,不加载缓存配置。
  * @param $name 缓存名称
  * @param $data 缓存数据
  * @param $filepath 数据路径(模块名称)caches/cache_$filepath/
  * @param $type 缓存类型[file,memcache,apc]
  * @param $config 配置名称
  * @param $timeout 过期时间
  */
 function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
return $cache->set($name, $data, $timeout, '', $filepath);
 }
/**
  * 读取缓存,默认为文件缓存,不加载缓存配置。
  * @param string $name 缓存名称
  * @param $filepath 数据路径(模块名称)caches/cache_$filepath/
  * @param string $config 配置名称
  */
 function getcache($name, $filepath='', $type='file', $config='') {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
     return $cache->get($name, '', '', $filepath);
 }
/**
  * 删除缓存,默认为文件缓存,不加载缓存配置。
  * @param $name 缓存名称
  * @param $filepath 数据路径(模块名称)caches/cache_$filepath/
  * @param $type 缓存类型[file,memcache,apc]
  * @param $config 配置名称
  */
 function delcache($name, $filepath='', $type='file', $config='') {
     pc_base::load_sys_class('cache_factory','',0);
     if($config) {
         $cacheconfig = pc_base::load_config('cache');
         $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
     } else {
         $cache = cache_factory::get_instance()->get_cache($type);
     }
     return $cache->delete($name, '', '', $filepath);
 }
摘自chaojie2009的专栏
http://www.bkjia.com/phpjc/478386.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/478386.htmltecharticle/** * 返回经addslashes处理过的字符串或数组 * @param $string 需要处理的字符串或数组 * @return mixed */ function new_addslashes($string){ if(!is_array($string)...
其它类似信息

推荐信息