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

PHP implements custom interception of Chinese strings-utf8 version

墨辰丷
Release: 2023-03-27 21:58:01
Original
1783 people have browsed it

This article mainly introduces the method of custom intercepting Chinese strings in PHP, which has a very good reference value. Let’s take a look at it with the editor.

First of all, please explain: There are currently a lot of codes for this problem on the Internet. , but many of them are copied and pasted without practice by myself, and the code has logic 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

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


Related recommendations:

php method to generate one or more groups of random strings

php preg_match matchStringLength case analysis

PHP preg_match matchStringDetailed explanation of length steps

The above is the detailed content of PHP implements custom interception of Chinese strings-utf8 version. 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