PHP string encoding intercept function (compatible utf-8 and gb2312) _php instance

Source: Internet
Author: User
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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.