This article introduces two functions in php that intercept Chinese strings without garbled characters, namely the ord () function and substr () function. For more information, see. Note in php Programming: according to the UTF-8 coding specification, count three consecutive characters as a single character. Let's take a look at the code for intercepting a Chinese string, as shown below:
= 224) // if the ASCII height is 224, {$ returnstr = $ returnstr. substr ($ sourcestr, $ I, 3); // count three consecutive characters as a single character according to the UTF-8 encoding specification $ I = $ I + 3; // The actual bytes are calculated as 3 $ n ++; // string length sensor 1} elseif ($ ascnum> = 192) // if the ASCII bit height is 192, {$ returnstr = $ returnstr. substr ($ sourcestr, $ I, 2); // Count 2 consecutive characters as a single character according to the UTF-8 encoding specification $ I = $ I + 2; // The actual Byte is calculated as 2 $ n ++; // string length gauge 1} elseif ($ ascnum> = 65 & $ ascnum <= 90) // if it is a capital letter, {$ returnstr = $ returnstr. substr ($ sourcestr, $ I, 1); $ I = $ I + 1; // The actual number of bytes is still 1 $ n ++; // but consider the overall appearance. uppercase letters are counted as a high character} else // In other cases, including lowercase letters and halfwidth punctuation marks, {$ returnstr = $ returnstr. substr ($ sourcestr, $ I, 1); $ I = $ I + 1; // The actual number of bytes is 1 $ n = $ n + 0.5; // lower-case letters, Halfwidth punctuation marks, and half-width upper-limit characters ...}} if ($ str_length> $ I) {$ returnstr = $ returnstr. "... "; // when the length is exceeded, add a ellipsis at the end} return $ returnstr ;} The code above allows you to cut UTF-8 encoded strings by words. if you want to cut a letter into a word, you need to cut $ n = $ n + 0.5; change to $ n = $ n + 1; In addition, it should be noted that php provides built-in processing functions, which can be implemented using mb_substr ($ str, int, int, 'utf-8. The parameters are respectively the target string $ str, starting to intercept the position int, intercepting the length int, and intercepting the character encoding (UTF-8 ). Return result: int characters from the start position (the start position is within the length. For example: $ Str = 'general rules can be widely used to cover both sides of the sofa exten'; echo mb_substr ($ str, 'utf-8 '); Output result: three words are overwritten. |