search
HomeBackend DevelopmentPHP TutorialHow to solve the php substr garbled problem

How to solve the php substr garbled problem

Nov 11, 2017 am 11:20 AM
phpsubstrquestion

php substr is a functional function developed based on the php language that can return a part of a string. Sometimes when we use php substr, some garbled characters will appear. How to solve it?

string substr ( string $string , int $start [, int $length ] )

Returns a string with a length of length starting from the start position in the string

The substr function intercepts characters by bytes. Chinese characters are 2 characters when encoded in GB2312 section, UTF-8 encoding is 3 bytes, so if Chinese characters are truncated when intercepting a string of specified length, the returned result will be garbled when displayed.

After checking, the solutions can be summarized into two categories:

1. Use the mb_substr() function instead

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

is similar to the substr() function, except Counting is based on the number of characters to ensure character safety

Using the mb_substr() function can ensure that there will be no garbled characters, but the disadvantage is that the length statistics become the number of characters instead of the number of bytes. When used for display, there will be a large difference in display length between Chinese results and English results of the same length.

2. Self-built function to enhance substr function

Here is a function that can better solve the problem of substr encountering Chinese characters. Chinese characters are calculated in 2 length units, so that the final display length of the string interception results in a mixed Chinese and English environment is close; the last incomplete character is discarded to ensure that there will be no garbled characters on the display; and it is compatible with UTF commonly used for Chinese characters -8 encoding and GB2312 encoding have good versatility.

View source code

  function getstr($string, $length, $encoding  = 'utf-8') {    
 $string = trim($string);    
 if($length && strlen($string) > $length) {    
  //截断字符    
  $wordscut = '';    
  if(strtolower($encoding) == 'utf-8') {    
  //utf8编码    
   $n = 0;    
  $tn = 0;    
 $noc = 0;    
 while ($n < strlen($string)) {    
  $t = ord($string[$n]);    
 if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {    
 $tn = 1;    
 $n++;    
  $noc++;    
 } elseif(194 <= $t && $t <= 223) {    
 $tn = 2;    
 $n += 2;    
} elseif(224 <= $t && $t < 239) {    
  $tn = 3;    
  $n += 3;    
  $noc += 2;    
 } elseif(240 <= $t && $t <= 247) {    
 $tn = 4;    
 $n += 4;    
 $noc += 2;    
 } elseif(248 <= $t && $t <= 251) {    
  $tn = 5;    
$n += 5;    
   $noc += 2;    
 } elseif($t == 252 || $t == 253) {    
 $tn = 6;    
   $n += 6;    
   $noc += 2;    
  } else {    
 $n++;    
}    
 if ($noc >= $length) {    
break;    
 }    
}    
 if ($noc > $length) {    
$n -= $tn;    
  }    
 $wordscut = substr($string, 0, $n);    
 } else {    
 for($i = 0; $i < $length - 1; $i++) {    
  if(ord($string[$i]) > 127) {    
$wordscut .= $string[$i].$string[$i + 1];    
$i++;    
 } else {    
   $wordscut .= $string[$i];    
  }    
 }    
  }    
$string = $wordscut;    
 }    
return trim($string);    
 }    
 // 示例    
 echo getstr("0一二三四五六七",1).&#39;<br />&#39;;  // 0    
 echo getstr("0一二三四五六七",2).&#39;<br />&#39;;  // 0    
echo getstr("0一二三四五六七",3).&#39;<br />&#39;;  // 0一    
 echo getstr("0一二三四五六七",4).&#39;<br />&#39;;  // 0一    
 echo getstr("0一二三四五六七",5).&#39;<br />&#39;;  // 0一二    
 echo getstr("0一a二b三四五六七",1).&#39;<br />&#39;;    // 0    
  echo getstr("0一a二b三四五六七",2).&#39;<br />&#39;;    // 0    
 echo getstr("0一a二b三四五六七",3).&#39;<br />&#39;;    // 0一    
 echo getstr("0一a二b三四五六七",4).&#39;<br />&#39;;    // 0一a    
  echo getstr("0一a二b三四五六七",5).&#39;<br />&#39;;    // 0一a

This function is modified from the getstr() function in UCHome 1.5.

The above is the solution on how to solve the problem of php substr garbled characters. We have also shared a series of articles about the php substr function before. If you need it, you can pay attention to the PHP Chinese website.

Related recommendations:

Several programs about PHP substr() function

php substr() function processing Chinese detailed explanation

php substr() function string interception usage example explanation


The above is the detailed content of How to solve the php substr garbled problem. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),