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")].
(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
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>"; ?>
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!