g236 PHP string encoding intercept function (compatible with utf-8 and gb2312)

Source: Internet
Author: User
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.

  • 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.