PHP intercepts utf-8 format string instance code _php instance

Source: Internet
Author: User
Tags strlen

PHP intercepts the Utf-8 format string

In PHP, we often need to intercept strings. The English character occupies a byte, the Chinese character occupies two bytes, but the Chinese character occupies two bytes is relative to the GBK encoding but in the current internationally popular UTF8 encoding, a Chinese character occupies 3 bytes. This article introduces a function of PHP to intercept utf-8 format strings.

An example is provided:

function truncate_utf8_string ($string, $length, $etc = ' ... ') {
 $result = ';
 $string = Html_entity_decode (Trim (strip_tags ($string)), ent_quotes, ' UTF-8 ');
 $strlen = strlen ($string);
 for ($i = 0; (($i < $strlen) && ($length > 0));  $i + +) {
 if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') {
  if ($length < 1.0) {break
  ;
  }
  $result. = substr ($string, $i, $number);
  $length-= 1.0;
  $i + + $number-1;
 } else {
  $result. = substr ($string, $i, 1);
  $length-= 0.5;
 }
 }
 $result = Htmlspecialchars ($result, ent_quotes, ' UTF-8 ');
 if ($i < $strlen) {
 $result. = $etc;
 }
 return $result;
}

If you need to intercept a string in utf-8 format, call this function directly.

<?php
  $str = "If you need to intercept strings in utf-8 format, call this function directly." ";
  Echo truncate_utf8_string ($STR, 10);//Output result: If you need to intercept utf-8 ...
? >

Thank you for reading, I hope to help you, thank you for your support for this site!

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.