PHP string truncation (supports Chinese)

巴扎黑
Release: 2016-11-23 14:41:01
Original
985 people have browsed it

<?php    
/**  
 * 字符串截长(支持中文)  
 * @author:zms  
 * @version:2011-7-27  
 */  
  
    /**  
     * 字符串截取  
     * @param object $str : 字符串(支持中文)  
     * @param object $start :截取开始位置  
     * @param object $length:截取结束位置  
     * @param object $encode [optional]:字符串编码  
     * @param object $input_encode [optional]:输入的文字的编码  
     * @return  
     */  
    function substring($str, $start, $length, $encode = &#39;utf-8&#39;, $input_encode = &#39;utf-8&#39;) {   
        //编码转换   
        $str = iconv($input_encode, $encode, $str);   
        //正则匹配   
        preg_match_all(getRege($encode), $str, $match);   
        //从数组取得数据,组成字符串   
        $slice = join("", array_slice($match[0], $start, $length));   
        return $slice;   
    }   
    /**  
     * 中文编码  
     * @param object $type  
     * @return  
     */  
    function getRege($type) {   
        $rege = "";   
        switch (strtolower($type)) {   
            case &#39;utf-8&#39;:   
                $rege = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";   
                break;   
            case &#39;gb2312&#39;:   
                $rege = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";   
                break;   
            case &#39;gbk&#39;:   
                $rege = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";   
                break;   
            case "big5":   
                $rege = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";   
                break;   
            default:   
                echo "charset error";   
                exit;   
        }   
        return $rege;   
    }   
?>
Copy after login

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!