php | Chinese-English mixed string interception

Source: Internet
Author: User
Tags 0xc0
PHP Notes | Mixed string interception in English

It is often necessary to intercept long content when a list of records is displayed on a Web page.

Using PHP built-in substr function on the Chinese and English mixed strings, especially the character encoding in the case of UTF-8, support is very bad, will appear garbled.

So I wrote a function:


function truncate ($string, $len, $wordsafe = FALSE) {$slen = strlen ($string), if ($slen <= $len) {return $string;} if ($wordsafe) {while ($string [--$len]! = ') && ($len > 0)) {};} if (Ord ($string [$len]) < 0x80) | | (Ord ($string [$len]) >= 0xC0)) {return substr ($string, 0, $len). "...";} while (Ord ($string [-$len]) < 0xC0) {};return substr ($string, 0, $len). "...";}


Tested successfully. yeah!



2012-06-15 Update:


Once again today, the benefit is that the two English characters will be treated as a character length:

So the length of the number of Chinese characters to be intercepted



function truncate ($string, $len, $cnCharWidth = 2) {$len = $len * $cnCharWidth; $suffix = "..."; $newStr = ""; for ($i = 0, $ j = 0; $i < $len; $i + +, $j + +) {if (!isset ($string [$j])) {$suffix = ""; break;} $start = $j; while ($j < ($start +3) &&! ( Ord ($string [$j]) < 0x80) {$j + +;} if ($start = = $j) {$charLen = 1;} else {$i = $i + 1; $j--; $charLen = 3;} $newStr. = substr ($string, $start, $charLen);} Return $NEWSTR. $suffix;}
  • 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: 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.