Home >php教程 >php手册 >php中中文截取函数mb_substr()详细

php中中文截取函数mb_substr()详细

WBOY
WBOYOriginal
2016-06-13 09:55:47974browse

由于中文是两个字节所以不能像英文和数字那样来用substr()这样会出现乱码,幸好在php有mb_substr()函数来处理这个问题,有需要的朋友看看。

一、中文截取:mb_substr()

mb_substr( $str, $start, $length, $encoding )

$str,需要截断的字符串
$start,截断开始处,起始处为0
$length,要截取的字数
$encoding,网页编码,如utf-8,GB2312,GBK

实例:

 代码如下 复制代码
$str='电影618:http://www.bKjia.c0m';
echo mb_substr($str,0,5,'utf-8');//截取头5个字,假定此代码所在php文件的编码为utf-8
?>

结果显示:电影618

二、获取中文长度:mb_strlen()

mb_strlen( $str, $encoding )

$str,要计算长度的字符串
$encoding,网页编码,如utf-8,GB2312,GBK

实例:

 代码如下 复制代码
$str='电影618:http://www.hzhuti.com';
echo mb_strlen($str,'utf-8');//假定此代码所在php文件的编码为utf-8
?>

结果显示:29

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn