在网站中调用新闻标题或者摘要的时候,为了布局美观,我们经常要截取一部分显示,但是截取中文字符时有时经出现乱码,现在我们来讲讲如何解决截取中文乱码的问题。
用PHP函数substr截取中文字符可能会出现乱码,主要是substr可能硬生生的将一个中文字符"锯"成两半。
解决办法:
1、使用mbstring扩展库的mb_substr截取就不会出现乱码了。
2、自己书写截取函数,但效率不如用mbstring扩展库来得高。
3、如果仅是为了输出截取的串,可用如下方式实现:substr($str, 0, 30).chr(0)。
substr()函数可以分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_substr()/mb_strcut的用法与substr()相似,只是在mb_substr()/mb_strcut最后要加入多一个参数,以设定字符串的编码,但是一般的服务器都没打开php_mbstring.dll,需要在php.ini在把php_mbstring.dll打开。
举个例子:
<?php echo mb_substr('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8'); ?>
输出:这样一来我的字
<?php echo mb_strcut('这样一来我的字符串就不会有乱码^_^', 0, 7, 'utf-8'); ?>
输出:这样一
mb_substr是按字来切分字符,而mb_strcut是按字节来切分字符,但是都不会产生半个字符的现象。
PHP实现中文字串截取无乱码的方法
<?php //此函数完成带汉字的字符串取串 function substr_CN($str, $mylen) { $len = strlen($str); $content = ''; $count = 0; for ($i = 0; $i < $len; $i++) { if (ord(substr($str, $i, 1)) > 127) { $content.= substr($str, $i, 2); $i++; // www.jbxue.com } else { $content.= substr($str, $i, 1); } if (++$count == $mylen) { break; } } echo $content; } $str = "34中华人民共和国56"; substr_CN($str, 3); //输出34中 ?>
教程链接:
随意转载~但请保留教程地址★

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot 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),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
