Home > Article > Backend Development > How to intercept Chinese string without garbled characters in PHP
Use the PHP built-in method mb_substr to intercept Chinese without garbled characters. It is very simple to use.
<?php $str = '我喜欢laravel or yii2'; echo mb_substr($str, 0, 1, 'utf8'); //输出 我 exit;
The mb_substr method has one more parameter than substr, which is used to specify the string encoding.
utf-8 encoding interception example
$str = '我like laravel or yii2'; echo mb_substr($str, 0, 2, 'utf8'); //输出 我I
There is no problem in mixing Chinese and English.
Friendly Tips
When using, pay attention to the encoding of the php file and the encoding when displaying the web page.
To use this mb_substr method, you need to know the encoding of the string in advance. If you don't know the encoding, you need to judge. The mbstring library also provides mb_check_encoding to check the string encoding, but it is not perfect yet.
The above is the detailed content of How to intercept Chinese string without garbled characters in PHP. For more information, please follow other related articles on the PHP Chinese website!