日期:2012-08-13  浏览次数:20500 次

<?
class useful{
 /*
  * 常用函数类
  * 作    者:多菜鸟
  * 联系邮箱:kingerq AT msn DOT com
  * 创建时间:2005-07-18
  * 来源:http://blog.csdn.net/kingerq
  */
 
 /*
  * 功能:格式化数字,以标准MONEY格式输出
  */
 
 function formatnumber($num){
  return number_format($num, 2, ".", ",");
 }
 
 /*
  * 功能:格式化文本,将\n转成<br>等
  * 参数:$string 来源字符串
  * 返回:处理后的字符串
  */
 function formatstring($string = ""){
  $string = preg_replace(array("/ /", "/ /"), array(" ", "  "), $string);
  return nl2br($string);
 }
 
 /*
  * 功能:格式化文本输出
  * 参数 $text 为需格式化的文本内容
  */
 function formatcontent($text){
  $trans = get_html_translation_table(HTML_SPECIALCHARS);
  $trans = array_flip($trans);
  $text = strtr($text, $trans);
  //$text = str_replace("\n", "<br>", $text);
  //$text = str_replace(" ", " ", $text);
  return $text;
 }
 
 /*
  * 将字节转换成Kb或者Mb
  * 参数 $num为字节大小
  */
 function bitsize($num){
  if(!preg_match("/^[0-9]+$/", $num)) return 0;
  return $num > 1024 ? ($num/1024 > 1024 ? round($num/1024/1024, 2)." Mb" : round($num/1024, 2)." Kb") : $num." 字节";
 }
 
 /*
  * 防注入处理(为变量加入斜杠)函数
  * 参数 $array 为防注入变量数组
  */
 function add_s(&$array){
  foreach($array as $key=>$value){
   if(!is_array($value)){
    $array[$key]=addslashes($value);
   }else{
    $this->add_s($array[$key]);
   }
  }
 }
 
 /*
  * 转换HTML特殊字符(表单提交的时候使用,防止恶意JS代码)
  * 参数 $array 为需转换的字符串或者数组
  */
 function specialhtml(&$array){
  if(is_array($array)){//数组处理
   foreach($array as $key=>$value){
    if(!is_array($value)){
     $array[$key]=htmlspecialchars($value);
    }else{
     $this->specialhtml($array[$key]);
    }
   }
  }else{
   $array = htmlspecialchars($array);
  }
 }
 
 /*
  * 可以避免乱码的截取汉字
  * 参数 $str 为字符串,$start 为开始字符,$len 结束字符
  * 返回截取后的字符
  */
 function msubstr($str, $start, $len) {
  $tmpstr = "";
  $strlen = $start + $len;
  for($i = 0; $i < $strlen; $i++) {
   if(ord(substr($str, $i, 1)) > 0xa0) {
    $tmpstr .= substr($str, $i, 2);
    $i++;
   } else
    $tmpstr .= substr($str, $i, 1);
  }
  return $tmpstr;
 }
 
 /*
  * 功能:综合提示JS代码输出
  * 参数 $msg 为提示信息
  *      $direct 为提示类型 0为提示(默认)1为提示刷新返回 2为提示返回
  * 输出提示代码并结束程序
  */
 function alert_msg($msg, $direct = "0"){
  switch($direct){
   case '0'://提示
    $script = "";
   case '1'://提示刷新返回
    $script = "location.href=\"".$_SERVER["HTTP_REFERER"]."\";";
    break;
   case '2'://提示返回
    $script = "history.back();";
    break;
   default://提示转向指定页面
    $script = "location.href=\"".$direct."\";";
  }
  echo "<script language='javascript'>window.alert('".$msg."');".$script."</script>";
  exit;
 }