The problem of garbled characters in the interception of PHP

Source: Internet
Author: User
PHP built-in function substr () can intercept a specified string, but it is only appropriate to intercept all English strings. If Chinese is present in the string, it is possible to cause garbled characters after interception, even in some scenarios, such as JSON encoding, which results in null output.

The reason is that each character in a different character set takes up the same number of bytes, such as 3 bytes per Chinese character in the UTF-8 encoding, 2 bytes for the GB2312 kanji, and 1 bytes in English. In fact, the last two parameters of substr () specify the number of bytes instead of the number of characters, so it is possible that the final character truncation is incomplete and the Chinese characters are garbled.

When you encounter a Chinese character interception, a better approach is to use the MB_SUBSTR ()/mb_strcut () function of the mbstring extension library. These two methods have one more parameter than substr () at the last position, which is used to specify the string encoding.
$str = ' No garbled world more harmonious '; echo "MB_SUBSTR:". Mb_substr ($str, 0, 7, ' utf-8 ');

Mb_substr is to divide the string by character, while Mb_strcut splits the string by byte, but does not produce a half-character phenomenon, so there is no Chinese garbled.

If you are prompted that the Mb_substr () method does not exist, the server does not open the Php_mbstring.dll extension and needs to open Php_mbstring.dll in the php.ini configuration file.

Extension=php_mbstring.dll
  • 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.