PHP string encoding interception function (compatible with utf-8 and gb2312)_PHP tutorial

WBOY
Release: 2016-07-21 15:46:18
Original
770 people have browsed it

Copy code The code is as follows:

//Intercept the length of the string. Supports utf-8 and gb2312 encoding. If it is gb2312, first convert it to utf-8, intercept it based on utf-8 and then convert it back
function cut_string($str,$from=1,$length=10,$code='utf- 8',$rear='...'){
if($code!='utf-8'){//Always convert the string to utf-8 encoding
$str=iconv( $code,'utf-8',$str);
}
$str_len=mb_strlen($str,'utf-8');//The length of the string
if($from>$ str_len){//If the starting position of interception is greater than the length of the string, intercept the following $length
$from=$str_len-$length+1;
$from=($from<1?1:$from) ;
}
//Compatible with ucs-4 encoding
$i=0;//Byte count
$from_i=0;//The byte position to start interception
$from_len= 0;//Start character position to intercept
$tag=true;//Mark whether $from_len has been assigned
for($temp_len=0;($temp_len-$from_len<$length)||$tag ;$temp_len++){
$byte_code=ord(substr($str,$i,1));//One byte encoding
if($temp_len+1==$from){//Record The starting byte position to start intercepting
                                                                                                                                                                                                                                       through It occupies a few bytes. UTF-8 is a variable length encoding. According to the first byte of each character, you can determine how many bytes the character occupies.
$i++;
}
if( $byte_code>191&&$byte_code<224){
                                                                            $i+=3;
}
if($byte_code>239&&$byte_code<248){
$i+=4;
}
if($byte_code>248&&$byte_code<252){
             $i+=5;
                                                                                                     f-8',$code,substr ($str,$from_i,$i-$from_i).$rear);
}





http://www.bkjia.com/PHPjc/320155.html

www.bkjia.com

true
http: //www.bkjia.com/PHPjc/320155.html

TechArticle

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!