看到有人要截取函数,提供个。
望高手指教
一般我们截取字符串,目的是在列表时标题保持长度相等,但是纯英文截取时候和纯中文截取时候,长度会有很大差异,汉字占两个字符长度的。。。。。。
所以偶弄的这个是等长截取
<?php
include('CutString.php');
//假设要从第二个字符开始截取10个汉字长度的字符串
//情况一:纯中文字符串
$_S1 = '我是中国人我爱我的祖国';
//情况二:英文或数字符号字符串
$_S2 = 'abcdefg1234567!@#$%^^&**(()_';
//情况三:混合中文字符串
$_S3 = '我是boy1234*%混合字符串';
//看看三次截取结果长度,是等长的
echo CutString($_S1, 10,2,1);
echo '<BR>';
echo CutString($_S2, 10,2,1);
echo '<BR>';
echo CutString($_S3, 10,2,1);
/***
中国人我爱我的祖国..
efg1234567!@#$%^^&*..
boy1234*%混合字符串..
***/
?>
默认位utf8编码,$_Encode随便设置则为gb2312编码
函数代码如下:
<?php
/***************************************************************************
* CutString.php
* ------------------------------
* Date : Oct 20, 2005
* Run : Php4.1.1, Php5.0
* Copyright : (C) 2005 - DreamSoft Co.,Ltd.
* Mail : Dream@Dreamsoft.Ca
* Author : Egmax
*
* 作用:中文截取
*
*
***************************************************************************/
function CutString($_String, $_Length, $_Start=0, $_Encode='UTF-8')
{
$v = 0;
if($_Encode == 'UTF-8')
{
$_Pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($_Pa, $_String, $_Rarray);
$_SLength = count($_Rarray[0]);
if($_SLength < $_Length) return $_String;
for($i=$_Start; $i<$_SLength; $i++)
{
if($v >= $_Length * 2 - 1) return $_RS.'..';
if(ord($_Rarray[0][$i]) > 129) $v += 2;
else $v++;
$_RS .= $_Rarray[0][$i];
}
} else {
$_Start = $_Start * 2;
$_Length = $_Length * 2;
$_Len = strlen($_String);
if($_Len < $_Length) return $_String;
$_Rstring= '';
for($i=$_Start; $i<$_Len; $i++)
{
if($v >= $_Length - 1) return $_Rstring.'..';
if(ord(substr($_String, $i, 1)) > 129) { $_Rstring .= substr($_String, $i, 2); $v += 2; $i++; }
else { $_Rstring .= substr($_String, $i, 1); $v++; }
}
return $_Rstring.'..';
}
}
?>
根据字体的不同可能看起来不等长,比如村子的字体,英文显得长点。。
在村子发代码格式有很大变化,可以下载附件。
[ 本帖最后由 剑枫 于 2006-11-28 04:52 PM 编辑 ]