Home > Backend Development > PHP Tutorial > PHP custom interception of Chinese string-utf8 version

PHP custom interception of Chinese string-utf8 version

高洛峰
Release: 2023-03-06 09:32:02
Original
1342 people have browsed it

First of all, please note: There are currently a lot of codes for this problem on the Internet, but many of them are copied and pasted without my own practice, and the code has logical problems. The following code is written by myself.

Not much to say

/**
   * 该函数是对于utf8编码
   * @author 2582308253@qq.com
   * @param string $str
   * @param int $start
   * @param int $length
   * @return string
   * @copyright 2017年2月27日下午1:46:10
   */
  function gbsubstr2($str, $start, $length) {
    $length = abs($length);
    $strLen = strlen($str);
    $len = $start + $length;
    $newStr = '';
    for($i = $start; $i < $len && $i < $strLen; $i++) {
      if(ord(substr($str, $i, 1)) > 0xa0) {
        //utf8编码中一个汉字是占据3个字节的,对于其他的编码的字符串,中文占据的字节各有不同,自己需要去修改这个数a
        $newStr .= substr($str, $i, 3);//此处a=3;
        $i+=2;
        $len += 2; //截取了三个字节之后,截取字符串的终止偏移量也要随着每次汉字的截取增加a-1;
      } else {
        $newStr .= substr($str, $i, 1);
      }
    }
    return $newStr;
  }
Copy after login

For more PHP custom interception of Chinese strings-utf8 version related articles, please pay attention to the PHP Chinese website!

Related articles:

A small function that inserts a string at a specified position in the string

PHP development skills (10)-Chinese How to implement string interception without garbled characters

Detailed code explanation of the calculation formula for string format through eval in php

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