English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

php Cut utf-8Example Code of Format String

php Cut utf-8formatted string

In PHP, we often need to truncate strings. English characters occupy one byte, and Chinese characters occupy two bytes, but this is relative to the GBK encoding. However, in the popular UTF8encoding, a Chinese character occupies3bytes. This article introduces a php truncation method for utf-8Format string function.

For example:

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;
 
  $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 cut utf-8format string, you can directly call this function.

<?php
  $str="If you need to cut utf-8format string, you can directly call this function.";
  8_string($str,10);//Output result: If you need to cut utf-8Format...
?>

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

You May Also Like