Home > php教程 > php手册 > mb_substr中文的截取小知识

mb_substr中文的截取小知识

WBOY
Release: 2016-05-25 16:37:48
Original
1005 people have browsed it

mb_substr函数是substr函数的升级版,mb_substr支持中文截取并且不会出现乱码问题,下面我来介绍一下mb_substr基础知识.

例,代码如下:

<?php 
$str = &#39;这样一来我的字符串就不会有乱码^_^&#39;; 
echo "mb_substr:" . mb_substr($str, 0, 7, &#39;utf-8&prime;); 
//结果:这样一来我的字 
echo "<br>"; 
echo "mb_strcut:" . mb_strcut($str, 0, 6, &#39;utf-8&prime;); 
//结果:这样
Copy after login

从上面的例子可以看出,mb_substr是按字来切分字符,而mb_strcut是按字节来切分字符,但是都不会产生半个字符的现象.

在实际使用过程中需要和mb_strlen配合使用,mb_strlen的使用方法和strlen类似,只是多了一个编码参数:mb_strlen("我是要被计算长度的字符","gbk");结果是11.

详细的使用例子,比如字符串超过20个就需要截取,代码如下:

if(mb_strlen($str, "gbk") >20) 
{ 
 
  $str = mb_substr($str, 0, 20, "gbk"); 
 
}
Copy after login

注意:确保你的Windows/system32下有php_mbstring.dll这个文件,没有就从你Php安装目录extensions里拷入Windows/system32里面.

2.在windows目录下找到php.ini打开编辑,搜索mbstring.dll,找到 ;extension=php_mbstring.dll把前面的;号去掉,这样mb_substr函数就可以生效了.


本文地址:

转载随意,但请附上文章地址:-)

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template