php 截取utf-8格式的字符串

php教程评论387 views阅读模式

这篇文章主要介绍了php 截取utf-8格式的字符串实例代码的相关资料,并附实例代码,需要的朋友可以参考下

php 截取utf-8格式的字符串

php中,我们经常需要截取字符串。英文字符占用一个字节,中文字符占用两个字节,但中文字符占用两个字节是相对于GBK编码而言但是在时下国际流行的UTF8编码中,一个中文字符占用3个字节。本文章向大家介绍一个php 截取utf-8格式字符串的函数。

举例说明:

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;
}

如果需要截取utf-8格式的字符串,直接调用这个函数即可。

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

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关推荐:

PHP实现APP微信支付案例解析

php魔法函数与魔法常量使用方法

PHP魔术方法之__call与__callStatic如何使用

以上就是php 截取utf-8格式的字符串的详细内容,更多请关注php教程网其它相关文章!

企鹅博客
  • 本文由 发表于 2020年9月1日 13:28:04
  • 转载请务必保留本文链接:https://www.qieseo.com/249884.html

发表评论