Copy CodeThe code is as follows:
intercepts the string length. Supports Utf-8 and gb2312 encoding. If it is gb2312, first turn it into Utf-8, intercept it on the basis of 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 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 Intercept start position is greater than the string length, intercept the back $length
$from = $str _len-$length +1;
$from = ($from <1?1: $from);
}
Compatible with UCS-4 encoding
$i =0;//byte Count
$from the byte position at which the _i=0;//begins to intercept
$from the character position at which the _len=0;//begins to intercept
$tag =true;//Flag $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 start byte position at 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, which can be determined by the first byte of each character to account for a few bytes of the character
$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 above describes the g236 PHP string encoding interception function (compatible with utf-8 and gb2312), including the g236 aspects of the content, I hope to be interested in PHP tutorial friends helpful.