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")
=========================================================================
13 | function msubstr( $str , $start =0, $length , $charset = "utf-8" , $suffix =true) |
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 ); |
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 . "…" ; |