PHP string encoding truncation functions (compatible with UTF-8 and gb2312 ). The copy code is as follows: truncates the string length. UTF-8 and gb2312 encoding are supported. If it is gb2312, convert it to UTF-8, extract it based on UTF-8, and then convert it back to functioncut.
The code is as follows:
// Intercept the string length. UTF-8 and gb2312 encoding are supported. If it is gb2312, convert it to UTF-8 first, extract 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'); // string length
If ($ from> $ str_len) {// if the starting position of the truncation is greater than the string length, extract 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 position of the starting part of the byte
$ From_len = 0; // The starting position of the truncated character
$ Tag = true; // indicates 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
If ($ temp_len + 1 = $ from) {// records the start byte location where the truncation starts.
$ From_ I = $ I; $ from_len = $ temp_len; $ tag = false;
}
If ($ byte_code> = 0 & $ byte_code <128) {// The character occupies several bytes, and UTF-8 is a variable-length encoding, based on the first byte of each character, it can be determined that the character occupies several bytes.
$ I ++;
}
If ($ byte_code> 191 & $ byte_code <224 ){
$ I + = 2;
}
If ($ byte_code> 223 & $ byte_code <240 ){
$ I + = 3;
}
If ($ byte_code> 239 & $ byte_code <248 ){
$ I + = 4;
}
If ($ byte_code> 248 & $ byte_code <252 ){
$ I + = 5;
}
If ($ byte_code> 252 & $ byte_code <255 ){
$ I + = 6;
}
}
Return iconv ('utf-8', $ code, substr ($ str, $ from_ I, $ I-$ from_ I). $ rear );
}
The http://www.bkjia.com/PHPjc/320155.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/320155.htmlTechArticle code is as follows: // capture the string length. UTF-8 and gb2312 encoding are supported. If it is gb2312, convert it to UTF-8 first, extract it based on UTF-8, and then convert it back to function cut...