PHP string Intercept Length customization method

Source: Internet
Author: User
Tags ord
Let's take a look at how to use PHP custom functions to intercept the length of the character we want to intercept, beyond the ellipsis to replace or hide it.


String Truncation Method:

//intercept string length function cut ($Str, $Length, $more =true) {//$STR to intercept string, $    Length is the global $s that needs to be intercepted;    $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 intercepted, the end of the string is appended with the ellipsis "..."} } return $s;} 

How to use:

$str = ' Take a look at where to intercept? '; Echo Cut ($STR, 1); Echo '
'; Echo Cut ($STR, 4); Echo '
'; Echo Cut ($str, 5); Echo '
'; Echo Cut ($str, 5,false); Echo '
'; $str = ' Mix English and Chinese to see hello? '; Echo Cut ($STR), Echo '
'; Echo Cut ($STR, 50);

Output:

See... Look... Look... Look at the mix of Chinese and English to see Hel ... A mix of Chinese and English look hello?

Explanation: The general UTF-8 format is 3 bytes, while GBK compatible gb2312 is generally 2 bytes, the above is UTF-8 encoded as an instance.

The third parameter, $more, allows you to toggle the ellipsis pattern, which is true with an ellipsis and false to no ellipsis.

  • Related Article

    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.