PHP intercepts strings in English. It is easy to use substr directly. Generally, no garbled characters are displayed. It is a little troublesome to use Chinese characters.
Two solutions are provided below:
(1) directly use the mb_substr () of the Multi-byte function library.CodeAs follows:
<? PHP
Echo mb_substr ($ STR, $ start, $ length, $ encoding );
Echo "<br/> ";
?>
This method is simple, fast, secure, beautiful, and tempting... It can be described in any word, but unfortunately my Godaddy host does not support it, so I have to find another way out.
(2) Write a function similar to mb_substr and call it directly. The code I found below is actually very simple.
<? PHP
Function Substr_cn ($ string_input, $ start, $ length)
{
/* Function:
* ThisAlgorithmUsed to intercept Chinese strings
* The function is truncated in units of a single complete character. That is, one English character and one Chinese character both represent a unit length.
* Parameters:
* The $ string parameter is the string to be truncated,
* The $ start parameter indicates the starting position of the part to be intercepted,
* The $ length parameter indicates the number of characters to be intercepted (one Chinese character or one English character)
* Return value:
* Returns the truncated result string.
**/
$ Str_input = $ string_input;
$ Len = $ length;
$ Return_str = "";
// Define an empty string
For ($ I = 0 ; $ I < 2 * $ Len + 2 ; $ I ++)
$ Return_str = $ return_str ."";
$ Start_index = 0 ;
// Calculate the start byte offset
For ($ I = 0 ; $ I <$ start; $ I ++)
{
If (Ord ($ str_input {$ start_index}> = 161 )) // Chinese
{
$ Start_index + = 2 ;
}
Else // English
{
$ Start_index + = 1 ;
}
}
$ Chr_index = $ start_index;
// Capture
For ($ I = 0 ; $ I <$ Len; $ I ++)
{
$ ASC = ord ($ str_input {$ chr_index });
If ($ ASC> = 161 )
{
$ Return_str {$ I} = CHR ($ ASC );
$ Return_str {$ I + 1 } = CHR (ord ($ str_input {$ chr_index + 1 }));
$ Len + = 1 ; // Add 1 to the end Condition
$ I ++; // Add 1 to the position offset
$ Chr_index + = 2 ;
Continue ;
}
Else
{
$ Return_str {$ I} = CHR ($ ASC );
$ Chr_index + = 1 ;
}
}
Return Trim ($ return_str );
} // End of substr_cn
?>