截取中文字符串的函数

来源:百度文库 编辑:神马文学网 时间:2024/06/13 03:59:07
自己刚才看了一个文档,初步写了一个如果有需要的可以改一改,嘿嘿
#cut string
#截取字符数
function string_cut($string,$length = 100){
if (strlen($string)<= $length){return $string;}
$j=0;
#get cut position
#根据所过字符长度确定最后字符的位置
$pos=$length-1;
#char of cut pos  is not chinese
#截取位置字符非汉字
if($string{$pos}<=128){$cut_string=substr($string,0,$length);}
#check chinese number total
#检查中文字符的字节数
for($i=0; $i < $length; $i++){
if (ord($string{$i}) >; 128){$j++;}
}
#the bytes number of  chinese char is even
#中文字符字节数为偶数
if(!($j%2)){
$cut_string=substr($string,0,$length);
}else{
$cut_string=substr($string,0,$length-1);
}
return $cut_string."...";
}
redor 回复于:2004-11-29 15:14:50
排版怎么那么难看了?
HonestQiao 回复于:2004-11-29 22:32:51
这个是标准的函数:
function Short_Text($title,$titlelen=20)
{
$len = strlen($title);
if ($len <= $titlelen):
$title = $title;
else:
$title = substr($title,"0","$titlelen");
$parity= 0;
for($i=0;$i<$titlelen;$i++){
$temp_str=substr($title,$i,1);
if(Ord($temp_str)>;127) $parity+=1;
}
if($parity%2==1) $title=substr($title,0,($titlelen-1))."...";
else $title=substr($title,0,$titlelen)."...";
endif;
return $title;
}
redor 回复于:2004-11-30 09:01:23
原理都一样的
深空 回复于:2004-11-30 20:28:19
楼上的,那不叫标准。下面这个,唠叨写的,用法和substr一样:
function c_substr($str, $start = 0) {
$ch = chr(127);
$p = array("/[\x81-\xfe]([\x81-\xfe]|[\x40-\xfe])/", "/[\x01-\x77]/");
$r = array("", "");
if(func_num_args() >; 2)
$end = func_get_arg(2);
else
$end = strlen($str);
if($start < 0)
$start += $end;
if($start >; 0) {
$s = substr($str,0,$start);
if($s[strlen($s)-1] >; $ch) {
$s = preg_replace($p,$r,$s);
$start += strlen($s);
}
}
$s = substr($str,$start,$end);
$end = strlen($s);
if($s[$end-1] >; $ch) {
$s = preg_replace($p,$r,$s);
$end += strlen($s);
}
return substr($str, $start, $end);
}