Home > Backend Development > PHP Tutorial > php intercepts strings in utf-8 format

php intercepts strings in utf-8 format

墨辰丷
Release: 2023-03-28 15:18:01
Original
1620 people have browsed it

This article mainly introduces the relevant information about the example code of php intercepting strings in utf-8 format, and attaches the example code. Friends in need can refer to it

php intercepts utf-8 format In the string

#php, we often need to intercept the string. English characters occupy one byte, and Chinese characters occupy two bytes. However, Chinese characters occupy two bytes relative to GBK encoding. However, in the internationally popular UTF8 encoding, one Chinese character occupies 3 bytes. This article introduces you to a PHP function that intercepts UTF-8 format strings.

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, &#39;0&#39;, STR_PAD_LEFT ), &#39;0&#39; )) {
  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, &#39;UTF-8&#39; );
 if ($i < $strlen) {
 $result .= $etc;
 }
 return $result;
}
Copy after login

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

<?php
  $str="如果需要截取utf-8格式的字符串,直接调用这个函数即可。";
  echo truncate_utf8_string($str,10);//输出结果:如果需要截取utf-8格...
?>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP implementation of APP WeChat payment case analysis

phpHow to use magic functions and magic constants

How to use PHP magic methods __call and __callStatic

The above is the detailed content of php intercepts strings in utf-8 format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template