iconv_substr截取php中英文混排字符串

 

php5中解决中英文混排字符串的函数包括iconv_substr() ,iconv_strpos() ,iconv_strlen()

 

 

 

============================================================

 

substr()函数可以分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_substr()/mb_strcut的用法与substr()相似,只是在mb_substr()/mb_strcut最后要加入多一个参数,以设定字符串的编码,但是一般的服务器都没打开php_mbstring.dll,需要在php.ini在把php_mbstring.dll打开。
举个例子:
<?php
echo mb_substr('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8');
?>
输出:这样一来我的字
<?php
echo mb_strcut('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8');
?>
输出:这样一
从上面的例子可以看出,mb_substr是按字来切分字符,而mb_strcut是按字节来切分字符,但是都不会产生半个字符的现象。

php5 用此函数: iconv_substr($rs[0][file_info],0,16,"GB2312")

 

 

 

=========================================================================

 

 

 

/**
02 * 字符串截取,支持中文和其他编码
03 *
04 * @static
05 * @access public
06 * @param string $str 需要转换的字符串
07 * @param string $start 开始位置
08 * @param string $length 截取长度
09 * @param string $charset 编码格式
10 * @param string $suffix 截断显示字符
11 * @return string
12 */
13function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
14{
15    if(function_exists("mb_substr"))
16         mb_substr($str, $start, $length, $charset);
17    elseif(function_exists('iconv_substr')) {
18         iconv_substr($str,$start,$length,$charset);
19    }
20    $re['utf-8']   = "/[/x01-/x7f]|[/xc2-/xdf][/x80-/xbf]|[/xe0-/xef][/x80-/xbf]{2}|[/xf0-/xff][/x80-/xbf]{3}/";
21    $re['gb2312'] = "/[/x01-/x7f]|[/xb0-/xf7][/xa0-/xfe]/";
22    $re['gbk']    = "/[/x01-/x7f]|[/x81-/xfe][/x40-/xfe]/";
23    $re['big5']   = "/[/x01-/x7f]|[/x81-/xfe]([/x40-/x7e]|/xa1-/xfe])/";
24    preg_match_all($re[$charset], $str, $match);
25    $slice = join("",array_slice($match[0], $start, $length));
26    if($suffix) return $slice."…";
27    return $slice;
28}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值