PHP string truncation length customization method

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.