PHP substr()函数可以 分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_substr() /mb_strcut的用法与substr()相似,只是在mb_substr()/mb_strcut最后要加入多一个参数,以设定字符串的编码,但是 一般的服务器都没打开php_mbstring.dll,需要在php.ini在把php_mbstring.dll打开。
举个例子:
复制代码 代码如下:
echo mb_substr('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8');
?>
复制代码 代码如下:
echo mb_strcut('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8');
?>
复制代码 代码如下:
mb_substr
mb_substr() returns the portion of str specified by the start and length parameters.
mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
mb_strcut
mb_strcut() returns the portion of str specified by the start and length parameters.
mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.
It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.
复制代码 代码如下:
$str = '我是一串比较长的中文-www.webjx.com';
echo "mb_substr:" . mb_substr($str, 0, 6, 'utf-8');
echo "
";
echo "mb_strcut:" . mb_strcut($str, 0, 6, 'utf-8');
?>