What should I do if php uses the substr() function to intercept a string and it appears garbled?

王林
Release: 2023-03-02 10:16:02
Original
3609 people have browsed it

php uses the substr() function to intercept strings and the solution to garbled characters is: use the mb_substr() function, because the substr() function only targets English characters. Specific usage: [mb_substr($str,0,2,"UTF8")].

What should I do if php uses the substr() function to intercept a string and it appears garbled?

(Recommended tutorial: php tutorial)

Cause analysis:

substr() function Only for English characters, if we want to split Chinese characters, we need to use the mb_substr() function.

Function introduction:

mb_substr() function returns a part of the string.

Syntax:

mb_substr(string $str, int $start[,int $length = NULL[, string $encoding = mb_internal_encoding()]]):string
Copy after login

Parameter introduction:

  • str Required. Extract a substring from this string

  • #start Required. Specifies where to start the string

  • length Optional. Specifies the length of the string to be returned. The default is until the end of the string

  • encoding Optional. Character Encoding. If omitted, the internal character encoding is used

Return value:

Returns the extracted portion of the string, or FALSE on failure, or an empty string.

Code implementation:

<?php
header("Content-Type: text/html; charset=utf-8");
$str="网站工作室欢迎您!";
echo mb_strlen($str,"UTF8")."<br>";
echo mb_substr($str,0,2,"UTF8")."<br>";
?>
Copy after login

The above is the detailed content of What should I do if php uses the substr() function to intercept a string and it appears garbled?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template