php5中解決中英文混排字符串的函數(shù)包括iconv_substr() ,iconv_strpos() ,**iconv_strlen()
substr()函數(shù)可以分割文字错沽,但要分割的文字如果包括中文字符往往會遇到問題,這時可以用mb_substr()/mb_strcut這個函數(shù),mb_substr()/mb_strcut的用法與substr()相似,只是在mb_substr()/mb_strcut最后要加入多一個參數(shù),以設(shè)定字符串的編碼高每,但是一般的服務(wù)器都沒打開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是按字節(jié)來切分字符阻肩,但是都不會產(chǎn)生半個字符的現(xiàn)象带欢。
php5 用此函數(shù): iconv_substr($rs[0][file_info],0,16,"GB2312")
* 字符串截取,支持中文和其他編碼
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
if(function_exists("mb_substr")){
if($suffix)
return mb_substr($str, $start, $length, $charset)."..";
else
return mb_substr($str, $start, $length, $charset);
}
elseif(function_exists('iconv_substr')) {
if($suffix)
return iconv_substr($str,$start,$length,$charset)."..";
else
return iconv_substr($str,$start,$length,$charset);
}
$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
$re['big5'] = "/[x01-x7f]|x81-xfe/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
if($suffix) return $slice."…";
return $slice;
}