PHP characters Intercept Chinese anti-garbled use. chr (0) workaround

Source: Internet
Author: User
PHP code

<?php    $len = +;    $text = "How will the long title of the news show only a few words in front, followed by ..." To replace it? ";    echo strlen ($text) <= $len? $text: (substr ($text, 0, $len). chr (0). " ....");    ? >

Chr (0) is not NULL

Null is nothing, and Chr (0) has a value of 0. 16 binary is 0x00, which means binary is 00000000

Although Chr (0) will not show anything, but he is a character.

When the Chinese character is truncated, according to the coding rules he always vlasov the other words in the back together as a Chinese character interpretation, which is the reason for garbled. A combination of 0x81 to 0xFF and 0x00 always shows as "empty"

According to this characteristic, a Chr (0) is appended to the result of substr to prevent garbled characters.

Note:

Encode first byte second byte

gb2312 0xa1-0xf7 0xa1-0xfe

GBK 0x81-0xfe 0x81-0xfe 0x40-0x7e

Big5 0xa1-0xf7 0x81-0xfe 0x40-0x7e

Another way:

PHP code

function Csubstr ($text, $limit) {        $s = ';        for ($i =0; $i < $limit 3; $i + +) {            $s. = Ord ($text [$i]) >127? $text [$i]. $text [+ + $i]: $text [$i];        }        return $s;    }

The above applies only to gb2312 encoding, if it is UTF-8, the 4th line should be changed to

PHP code

$s. = Ord ($text [$i]) >127? $text [$i]. $text [+ + $i]. $text [+ + $i]: $text [$i];

The kanji in UTF-8 is 3 bytes.

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