search
HomeBackend DevelopmentPHP TutorialUsing ord in php to intercept Chinese strings and solve the problem of garbled characters_PHP tutorial

Using ord in php to intercept Chinese strings and solve the problem of garbled characters_PHP tutorial

Jul 13, 2016 am 10:55 AM
ordphpunderChineseGarbled charactersexampleusestringaccomplishusinterceptsolvequestion

Below we give two examples, both of which use ord to judge character ascii to avoid the problem of Chinese garbled characters. For the function of this function, we can refer to http://www.bKjia.c0m/phper/php/41030. htm article, which gives a good introduction to the use of this function.

//s character short integer 2 bytes
$str=(pack("s", "100"));
echo $str,"=",strlen($str),"byte n";
getascill($str);
The code is as follows
 代码如下 复制代码

//a字符
$str=(pack("a*", "中国"));
echo $str,"=",strlen($str),"字节n";
getascill($str);
//h字符
$str=(pack("h*", "fffe"));
echo $str,"=",strlen($str),"字节n";
getascill($str);
//c字符
$str=(pack("c*", "55","56","57"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

//i字符 短整形 32位 4个字节 64位8个字节
$str=(pack("i", "100"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

//s字符 短整形 2个字节
$str=(pack("s", "100"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

//l字符 长整形 4个字节
$str=(pack("l", "100"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

//f字符 单精度浮点 4个字节
$str=(pack("f", "100"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

//d字符 双精度浮点 8个字节
$str=(pack("d", "100"));
echo $str,"=",strlen($str),"字节n";
getascill($str);

function getascill($str)
{
$arr=str_split($str);
foreach ($arr as $v)
{
echo $v,"=",ord($v),"n";
}
echo "=============rnrn";
}
?>

Copy code

//a character
$str=(pack("a*", "China"));
echo $str,"=",strlen($str),"byte n";
getascill($str);
//h character
$str=(pack("h*", "fffe"));
echo $str,"=",strlen($str),"byte n";
getascill($str);
//c character
$str=(pack("c*", "55","56","57"));
echo $str,"=",strlen($str),"byte n";
getascill($str);

 代码如下 复制代码


/*
@ 另一种方法,使用ord()函数:
@ 适用于 gb2312 编码:
*/
$str = "怎么将新闻的很长的标题只显示前面一些字,后面用.....来代替?";
function gb2312_substr($str, $limit) {
$restr ='';
for($i=0;$i $restr .= ord($str[$i])>127 ? $str[$i].$str[++$i] : $str[$i];
}
return $restr;
}
/*
@ 以下仅适用于 utf-8 编码;
*/
function utf8_substr($str, $limit) {
$restr = '';
for($i=0;$i $restr .= ord($str[$i])>127 ? $str[$i].$str[++$i].$str[++$i] : $str[$i];
}
return $restr;
}
//解释下上面第一个:chr(0)不是null,null是什么都没有,而chr(0)的值是0。表示成16进制是0x00,表示成二进制是00000000虽然chr(0)不会显示出什么,但是他是一个字符。虽然chr(0)不会显示出什么,但是他是一个字符。当汉字被截断时,根据编码规则他总是要把后边的其他字符拉过来一起作为汉字解释,这就是出现乱码的原因。
?>

//i character short integer 32 bits 4 bytes 64 bits 8 bytes
$str=(pack("i", "100"));
echo $str,"=",strlen($str),"byte n";
getascill($str);
//l character long integer 4 bytes
$str=(pack("l", "100"));
echo $str,"=",strlen($str),"byte n";
getascill($str);

//f character single precision floating point 4 bytes
$str=(pack("f", "100"));
echo $str,"=",strlen($str),"byte n";
getascill($str);//d character double precision floating point 8 bytes
$str=(pack("d", "100"));
echo $str,"=",strlen($str),"byte n";
getascill($str); function getascill($str)
{
$arr=str_split($str);
foreach ($arr as $v)
{
echo $v,"=",ord($v),"n";
}
echo "=============rnrn";
}
?> For more details, please check: http://www.bKjia.c0m/phper/php-function/php-ord.htm Example 2
The code is as follows Copy code

/*
@ Another way, use the ord() function:
@ Applies to gb2312 encoding:
*/
$str = "How to display only the first few words of a long news title and replace it with...?";
function gb2312_substr($str, $limit) {
$restr ='';
for($i=0;$i $restr .= ord($str[$i])>127 ? $str[$i].$str[++$i] : $str[$i];
}
return $restr;
}
/*
@The following only applies to utf-8 encoding;
*/
function utf8_substr($str, $limit) {
$restr = '';
for($i=0;$i $restr .= ord($str[$i])>127 ? $str[$i].$str[++$i].$str[++$i] : $str[$i]; }
return $restr;
}
//Explain the first one above: chr(0) is not null, null means nothing, and the value of chr(0) is 0. Expressed as hexadecimal, it is 0x00, and expressed as binary, it is 00000000. Although chr(0) will not display anything, it is a character. Although chr(0) does not display anything, it is a character. When a Chinese character is truncated, according to the encoding rules, he always has to pull the other characters behind as Chinese characters for interpretation. This is the reason why garbled characters appear.
?>
http://www.bkjia.com/PHPjc/632246.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632246.htmlTechArticle Below we give two examples, both of which use ord to instantiate character ascii judgment to avoid the problem of Chinese garbled characters. For the function of this function, we can refer to http://www.111cn.net/phper/php/4103...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.