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).'<br />'; // 0 echo getstr("0一二三四五六七",2).'<br />'; // 0 echo getstr("0一二三四五六七",3).'<br />'; // 0一 echo getstr("0一二三四五六七",4).'<br />'; // 0一 echo getstr("0一二三四五六七",5).'<br />'; // 0一二 echo getstr("0一a二b三四五六七",1).'<br />'; // 0 echo getstr("0一a二b三四五六七",2).'<br />'; // 0 echo getstr("0一a二b三四五六七",3).'<br />'; // 0一 echo getstr("0一a二b三四五六七",4).'<br />'; // 0一a echo getstr("0一a二b三四五六七",5).'<br />'; // 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!

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.

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

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

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.

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.

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

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,

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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),
