天天看点

中文字符串截取(mb_substr)和获取字数(mb_strlen)中文字符串截取(mb_substr)和获取字数(mb_strlen)

中文字符串截取(mb_substr)和获取字数(mb_strlen)

一、中文截取:mb_substr()

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

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

实例:

<?php 
$str='InE 博客频道:http://blog.csdn.net/qq_22253823'; 
//截取头7个字,假定此代码所在php文件的编码为utf-8 
echo mb_substr($str,,,'utf-8');
?> 
结果显示:InE博客频道
           

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

mb_strlen( $str, $encoding )

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

实例:

<?php 
$str='InE 博客频道:http://blog.csdn.net/qq_22253823'; 
//假定此代码所在php文件的编码为utf-8 
echo mb_strlen($str,'utf-8');
?> 
结果显示:40