Home > php教程 > php手册 > php mb_substr实现中文字符串截取无乱码的方法

php mb_substr实现中文字符串截取无乱码的方法

WBOY
Release: 2016-05-24 13:25:27
Original
899 people have browsed it

在网上看到有很多字符截取函数大仔细研究了一下发现所有的都是针对编码问题进行处理了,下面我们看一个简化的函数,希望对大家有帮助.

注意:在windows目录下找到php.ini打开编辑,搜索mbstring.dll,找到:

;extension=php_mbstring.dll,把前面的;号去掉,这样mb_substr函数就可以生效了.

php例子代码如下:

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

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

/** 
 *   实现中文字串截取无乱码的方法 
 */ 
function getSubstr($string, $start, $length) { 
    if(mb_strlen($string,&#39;utf-8&#39;)>$length){ 
        $str = mb_substr($string, $start, $length,&#39;utf-8&#39;);  
        return $str.&#39;...&#39;;//开源代码phprm.com 
    }else{
        return $string; 
    }
}
Copy after login


教程链接:

随意转载~但请保留教程地址★

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