Home  >  Article  >  Backend Development  >  PHP截取中文字符串乱码问题解决

PHP截取中文字符串乱码问题解决

WBOY
WBOYOriginal
2016-06-20 13:04:291137browse

PHP截取中文字符串乱码问题解决

在CMS内容文章系统或者是新闻系统中,经常需要进行字符串截取来进行页面排版,所以下面介绍简单的中文字符串截取不乱码的方法:

/**<br />	     * <br />	     * @todo 截取中文字符串不乱码<br />	     * @param string $str<br />	     * @param int $start<br />	     * @param int $length<br />	     * @param string $charset<br />	     * @param string $suffix<br />	     */<br />	    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {<br />	        if(function_exists("mb_substr"))<br />	            $slice = mb_substr($str, $start, $length, $charset);<br />	        elseif(function_exists('iconv_substr')) {<br />	            $slice = iconv_substr($str,$start,$length,$charset);<br />	        }else{<br />	            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";<br />	            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";<br />	            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";<br />	            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";<br />	            preg_match_all($re[$charset], $str, $match);<br />	            $slice = join("",array_slice($match[0], $start, $length));<br />	        }<br />	        return $suffix ? $slice.'...' : $slice;<br />	    }   
  

该处是引用的THINKPHP中的中文字符串截取,还是蛮实用的!


Statement:
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