Home  >  Article  >  Backend Development  >  How to solve the problem of php byte loss and garbled characters

How to solve the problem of php byte loss and garbled characters

藏色散人
藏色散人Original
2021-12-08 10:09:162120browse

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.

How to solve the problem of php byte loss and garbled characters

#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn