PHP substr 截取中文乱码的问题解决办法
在php中为我们提供了几个字符截取函数,包括substr,mb_substr,mb_strcut函数,我们有些php初学者会利用substr来截取中文,结果发现中文会有乱码了,出现乱码我们可以使用mb_substr来解决。
文章页面的 description 是使用 substr 函数来截取220字符的,但是最后一个汉字总是乱码,而且截取出来的长度也不正确。
通过神奇的 Google 找到方法,可能是因为 substr(string,start,length),会将汉字以字符的形式截断,而造成乱码
解决方案:
使用 PHP 扩展库中的 mb_substr 方法。
注意
1.确保你的Windows/system32下有php_mbstring.dll这个文件,没有就从你Php安装目录extensions里拷入Windows/system32里面。
2.在windows目录下找到php.ini打开编辑,搜索mbstring.dll,找到
;extension=php_mbstring.dll把前面的;号去掉,这样mb_substr函数就可以生效了
方法定义:
string mb_substr ( string str, int start [, int length [, string encoding]] )
注意:在使用 mb_substr()/mb_strcut 最后要加入多一个参数,以设定字符串的编码,
例如:
代码如下 | 复制代码 |
echo mb_substr(‘原本会出现乱码的汉字!’, 0, 7, ‘utf-8′); |
再如:
代码如下 | 复制代码 |
$description = mb_substr(strip_tags($post->post_content),0,220,’utf-8′); |
mb_strcut函数
mb_strcut函数功能也可以截取字符串长度,下面实例具体看看区别在哪:
代码如下 | 复制代码 |
$str = '这样一来我的字符串就不会有乱码^_^'; echo "mb_substr:" . mb_substr($str, 0, 7, 'utf-8'); echo "mb_strcut:" . mb_strcut($str, 0, 6, 'utf-8'); |
从上面的例子可以看出,mb_substr是按字来切分字符,而mb_strcut是按字节来切分字符,但是都不会产生半个字符的现象。
substr()函数中文版 普通的substr()函数可以取得字符串的指定长度子字符串,但遇到中文时可能会在新字符串末尾产生乱码,下面这个函数将超过$len长度的字符串转换成以“...”结尾,并且去除了乱码。
用法:$new = getsubstring($old,20);
代码如下 | 复制代码 |
function getsubstring($str,$len) { for($i = 0;$i { if ($i >=0 AND $i { if(ord(substr($str,$i,1)) > 0xa1) $result_str.=substr($str,$i,2); else $result_str.=substr($str,$i,1); } if(ord(substr($str,$i,1)) > 0xa1) $i++; } if(strlen($str) return $result_str; else return $result_str."..."; } |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment