The substr () function returns part of the string.
Syntax
Substr (string, start, length)
Example 1
| The code is as follows: |
Copy code |
<? Php Echo substr ("Hello world! ", 6 ); ?> Output: World! |
Example 2
| The code is as follows: |
Copy code |
Echo substr ('China', 1 ); |
The result is a chip. Later I learned that the difference between Chinese and English is the internal encoding. A website says that the substr function intercepts characters in bytes, chinese characters are encoded in GB2312 as two bytes, and UTF-8 as three bytes. Therefore, if Chinese characters are truncated when a string of the specified length is intercepted, garbled characters are displayed in the returned results.
Solution
1. Use mb_substr to intercept
| The code is as follows: |
Copy code |
<? Php $ Str = 'so that my string will not contain garbled characters ^_^ '; Echo "mb_substr:". mb_substr ($ str, 0, 7, 'utf-8 '); // Result: Echo "<br> "; Echo "mb_strcut:". mb_strcut ($ str, 0, 6, 'utf-8 '); // Result: ?> |
However, if you want to use mb_substr to intercept data, you need to use the mbstring Extension Library. If you do not have the permission, you can refer to the following function.
| The code is as follows: |
Copy code |
Function msubstr ($ str, $ start, $ len ){ $ Tmpstr = ""; $ Strlen = $ start + $ len; For ($ I = 0; $ I <$ strlen; $ I ++ ){ If (ord (substr ($ str, $ I, 1)> 0xa0 ){ $ Tmpstr. = substr ($ str, $ I, 2 ); $ I ++; } Else $ Tmpstr. = substr ($ str, $ I, 1 ); } Return $ tmpstr; } |