Home > Article > Backend Development > g236 PHP string encoding interception function (compatible with utf-8 and gb2312)
Copy the 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 interception starting position is greater than the string Length, intercept the following $length
$from=$str_len-$length+1;
$from=($from<1?1:$from);
}
;//Byte count
$from_i=0;//The byte position where interception begins
$from_len=0;//The character position where interception begins
$tag=true;//Marks whether $from_len has been assigned a value
for ($temp_len=0;($temp_len-$from_len<$length)||$tag;$temp_len++){
$byte_code=ord(substr($str,$i,1));//One byte encoding
0&&$byte_code<128){//How many bytes does a character occupy? UTF-8 is a variable-length encoding. Based on the first byte of each character, you can determine how many bytes the character occupies.
{
$i+=3;
$byte_code<248){
}
i+=6;
}
}
return iconv('utf-8',$code,substr($str,$from_i,$i-$from_i).$rear);
}
The above has introduced the g236 PHP string encoding interception function (compatible with utf-8 and gb2312), including g236 content. I hope it will be helpful to friends who are interested in PHP tutorials.