PHP string truncation length custom method cut _ with ellipsis we will introduce how to use PHP custom functions to intercept the length of the characters we want to intercept. the excess part should be replaced or hidden by ellipsis.
String truncation method:
// Function cut ($ Str, $ Length, $ more = true) of the truncated string {// $ Str is the truncated string, and $ Length is the global $ s; $ I = 0; $ l = 0; $ ll = strlen ($ Str); $ s = $ Str; $ f = true; while ($ I <= $ ll) {if (ord ($ Str {$ I}) <0x80) {$ l ++; $ I ++ ;} else if (ord ($ Str {$ I}) <0xe0) {$ l ++; $ I + = 2;} else if (ord ($ Str {$ I }) <0xf0) {$ l + = 2; $ I + = 3;} else if (ord ($ Str {$ I}) <0xf8) {$ l + = 1; $ I + = 4;} else if (ord ($ Str {$ I}) <0xfc) {$ l + = 1; $ I + = 5 ;} else if (ord ($ Str {$ I}) <0xfe) {$ l + = 1; $ I + = 6 ;} if ($ l >=$ Length-1) & $ f) {$ s = substr ($ Str, 0, $ I); $ f = false ;} if ($ l> $ Length) & ($ I <$ ll) & $ more) {$ s = $ s. '... '; break; // if the string is intercepted, the omitted symbol "... "} return $ s ;}
Usage:
$ Str = 'Where can I find the screenshot? '; Echo cut ($ str, 1); echo'
'; Echo cut ($ str, 4); echo'
'; Echo cut ($ str, 5); echo'
'; Echo cut ($ str, 5, false); echo'
'; $ Str =' mix Chinese and English to see hello? '; Echo cut ($ str, 18); echo'
'; Echo cut ($ str, 50 );
Output:
Let's take a look at... let's take a look at the mix of Chinese and English. let's take a look at the combination of Chinese and English?
Description: generally, the UTF-8 format is 3 bytes, while GBK is compatible with gb2312 is generally 2 bytes, the above is an example of UTF-8 encoding.
You can use the third parameter $ more to switch to the ellipsis mode. the default value true is with ellipsis, and false is without ellipsis.