Home  >  Article  >  Backend Development  >  How to intercept Chinese string without garbled characters in PHP

How to intercept Chinese string without garbled characters in PHP

silencement
silencementOriginal
2019-09-26 10:01:232964browse

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 = &#39;我喜欢laravel or yii2&#39;;
echo mb_substr($str, 0, 1, &#39;utf8&#39;); //输出 我
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 = &#39;我like laravel or yii2&#39;;
echo mb_substr($str, 0, 2, &#39;utf8&#39;); //输出 我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!

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
Previous article:Where to run the php fileNext article:Where to run the php file