PHP substr(),mb_substr()及mb_strcut的区别和用法

PHP 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是按字节来切分字符,但是都不会产生半个字符的现象……

举个例子,有一段文字, 分别用mb_substr和mb_strcut来做切分:

PLAIN TEXT
CODE:
<?php
$str = '我是一串比较长的中文-www.webjx.com';
echo "mb_substr:" . mb_substr($str, 0, 6, 'utf-8');
echo "<br>";
echo "mb_strcut:" . mb_strcut($str, 0, 6, 'utf-8');
?>
输出结果如下:

mb_substr:我是一串比较
mb_strcut:我是

原文地址:https://www.cnblogs.com/suizhikuo/p/2819752.html