Detailed explanation of the judgment and interception examples of mixed Chinese and English string lengths in PHP

怪我咯
Release: 2023-03-12 14:18:01
Original
1685 people have browsed it

This article mainly introduces PHP's length judgment and interception methods for mixed Chinese and English strings , and analyzes the traversal , conversion, and interception of Chinese and English strings in PHP in the form of examples. , calculation and other related operating skills, friends in need can refer to the following

This article describes the PHP method for length judgment and interception of mixed Chinese and English strings. Share it with everyone for your reference, the details are as follows:

/**
 * 
 * 中英混合字符串长度判断 
 * @param unknown_type $str
 * @param unknown_type $charset
 */
function strLength($str, $charset = 'utf-8') {
  if ($charset == 'utf-8')
    $str = iconv ( 'utf-8', 'gb2312', $str );
  $num = strlen ( $str );
  $cnNum = 0;
  for($i = 0; $i < $num; $i ++) {
    if (ord ( substr ( $str, $i + 1, 1 ) ) > 127) {
      $cnNum ++;
      $i ++;
    }
  }
  $enNum = $num - ($cnNum * 2);
  $number = ($enNum / 2) + $cnNum;
  return ceil ( $number );
}
Copy after login
rrree

The above is the detailed content of Detailed explanation of the judgment and interception examples of mixed Chinese and English string lengths in PHP. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!