Home > Article > Backend Development > How to solve the problem of php byte loss and garbled characters
Solutions to php byte loss and garbled characters: 1. Use the "mb_substr($str, 0, 1, 'gbk');" method to intercept Chinese strings; 2. Use "mb_substr($str, 0 , 2, 'utf-8');" method to intercept Chinese strings.
#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.
How to solve the problem of php byte loss and garbled characters?
php removes garbled characters caused by byte loss in the string
Use PHP's built-in method mb_substr to intercept without garbled characters;
1. GBK encoding interception example:
$str = '我是谁'; //gbk编码的字符串 echo mb_substr($str, 0, 1, 'gbk'); //输出 我
The mb_substr method has one more parameter than substr, which is used to specify the string encoding.
2. UTF-8 encoding interception example:
$str = '我abc是谁'; //utf-8编码的字符串 echo mb_substr($str, 0, 2, 'utf-8'); //输出 我a
There is no problem in mixing Chinese and English.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to solve the problem of php byte loss and garbled characters. For more information, please follow other related articles on the PHP Chinese website!