Copy Code code as follows:
intercepts the string length. Supports Utf-8 and gb2312 encodings. If for gb2312, first turn it into Utf-8, intercept on utf-8 basis and then convert back
function cut_string ($str, $from =1, $length =10, $code = ' utf-8 ', $rear = ' ... ') {
if ($code!= ' utf-8 ') {//Always convert string to UTF-8 encoding
$str =iconv ($code, ' utf-8 ', $str);
}
$str _len=mb_strlen ($str, ' utf-8 ');//Length of string
if ($from > $str _len) {//If the Intercept start position is greater than the string length, the $length behind the Intercept
$from = $str _len-$length +1;
$from = ($from <1?1: $from);
}
Compatible UCS-4 encoding
$i =0;//byte Count
$from the byte position at which _i=0;//begins to intercept
$from the character position where _len=0;//begins to intercept
$tag =true;//Flag $from_len Whether it has been assigned
for ($temp _len=0; ($temp _len-$from _len< $length) | | $tag; $temp _len++) {
$byte _code=ord (substr ($str, $i, 1));//byte encoding
if ($temp _len+1== $from) {//Start byte position of record start intercept
$from _i= $i $from _len= $temp _len; $tag =false;
}
if ($byte _code>=0&& $byte _code<128) {//character is a few bytes, utf-8 is a variable-length encoding that can be judged by the first byte of each character for 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);
}