Php string truncation user-defined functions are commonly used in the development process. generally, php built-in functions are also used, but they are not particularly useful, in particular, the support for Chinese characters is not very friendly, so we can customize it ourselves. Php string truncation user-defined functions are commonly used in the development process. generally, php built-in functions are also used, but they are not particularly useful, in particular, the support for Chinese characters is not very friendly, so we can customize it ourselves.
// $ Str is the truncated string, and $ Length is the function cut ($ Str, $ Length, $ more = true) {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 ;}
The calling method is very simple. you can directly call the method name in a common PHP file:
cut();
This is enough, but the parameter must be passed in. generally, 1st and 2nd are required, and 3rd are optional.
For example, if we want to extract the first 10 men from a string, we call
cut($str,10);
$ Str is the string to be captured, and 10 is the length.
By default, if the length before the truncation exceeds the length after the truncation, the excess function uses '...' by default to replace the subsequent string.
If we do not want to replace the excess part with '...', we only need to add a parameter 'false' later, as shown in figure
cut($str,10,false);