<?php
/*---------------------------------------------------------
 * File:string.php
 * Author:Tomix
 * Description:
 * Created:2009-7-8
 * -------------------------------------------------------
 * Modified history:
 * -------------------------------------------------------
 * Copyright:
 * -------------------------------------------------------
 */
 class string
 {
 	//計算utf-8字符串長度
 	static public function strlen($str)
 	{
 		return mb_strlen($str,"utf-8");
 	}

 	//返回utf-8子字符串
 	static public function substr($str,$start=0,$legth=-1)
 	{
 		if($legth < 0)
 			$legth=self::strlen($str);
 		return mb_substr($str,$start,$legth);
 	}

 	//字符串是空或null
 	static function isEmptyOrNull($str)
 	{
 		if($str == "" || $str == null)
 			return true;
 		return false;
 	}


	static public function cut_str($msg,$cut_size,$charset="UTF-8",$suffix="...")
	{
		//验证截取个数,如果是0将不截取
		if($cut_size<=0)
	     return $msg;

	    $i=1;
	    $han="";
	    $eng="";
		while ($i <= strlen($msg))
		{
			//判断是否是ASCII扩展字符
			if(ord($msg[($i-1)])>127)
			{
			  $han++;
		      if($charset=="UTF-8")
			  {
			     $str .=$msg[($i-1)].$msg[($i)].$msg[($i+1)];

		         //如果是UTF-8跳过3个ASCII
		         $i=$i+3;
		      }
			  else
			  {
		        $str .=$msg[($i-1)].$msg[($i)];
		        $i=$i+2;
		      }

		    }
			else
			{
				$eng++;
         		$str .=$msg[($i-1)];
				$i++;
		  }

		 //如果汉字和英文总和等于要截取的字符个数那么跳出循环
		 if(($han+$eng)==$cut_size)
		  {
			 break;
		  }
		}

		//如果汉字和英文总和等于要截取的字符个数那么不显示后缀
		$suffix = ($han+$eng)<$cut_size?"":$suffix;
		return $str.$suffix;
		}
 }
?>
