Home Backend Development PHP Tutorial PHP函数篇之掌握ord()与chr()函数应用_PHP

PHP函数篇之掌握ord()与chr()函数应用_PHP

Jun 01, 2016 pm 12:14 PM
ord

中文字符编码研究系列第三期,PHP函数篇掌握ord()与 chr()函数应用,上期[PHP基础篇详解ASCII码对照表与字符转换]一文中了解了ASCII码和字符转换的方法,但使用时发现在字符转换之间需要两个特殊的函数,用于字符与十进制之间的转换,ord()函数把字符转换为十进制数字,chr()函数把十进制数字转化为字符,在二进制,八进制,十进制与十六进制之间充当桥梁的作用。

一,ord()函数的应用
ord()函数用于返回一个字符的ASCII值,最基本的用法如获取a 的ASCII值ord('a')返回 97,但在实际开发中,应用最多的还是用于字符截取函数中获取中文字符高低位编码的十进制数,如常见的中文字符截取函数具体可看看PHPWind或 Discuz!论坛源代码中substrs()函数或cutstr()函数,其原理就是通过ord()函数获取字符的ASCII码值,如果返回值大于 127则表示为中文字符的一半,再获取后一半组合成一个完整字符,同时结合字符编码如GBK或UTF-8等。

以GBK编码为例利用ord()函数判断中文字符返回各中文字符的ASCII值,代码如下
复制代码 代码如下:
$string = "不要迷恋哥";
$length = strlen($string);
var_dump($string);//原始中文
var_dump($length);//长度
$result = array();
for($i=0;$iif(ord($string[$i])>127){
$result[] = $string[$i].' '.$string[++$i];
}
}
var_dump($result);

代码说明
1,定义一个变量$string,其值为字符串
2,获取变量的长度(字节数)
3,打印变量和变量的长度
4,通过for循环获取变量的各个字节值,把一个汉字的两个字节中间用空格隔开显示。
结果如下图
php-ord-dec
图解:“不要迷恋哥”为5个汉字,共10个字节(一个汉字2个字节),分别打印各个字节无法正常显示如上图

初始值不变修改for循环部分代码显示各个字节ASCII值
复制代码 代码如下:
$result = array();
for($i=0;$iif(ord($string[$i])>127){
$result[] = ord($string[$i]).' '.ord($string[++$i]);
}
}
var_dump($result);

如上代码使用ord()函数打印各个字符的ASCII值,结果如下
php-ord-dec-number
通过ord()函数转换后就能正常查看各个字符的ASCII值。

二,chr()函数的应用

chr()函数的作用与ord()函数相反,用于返回指定的字符,如chr(97)返回a。

结合上面实例,只要获取到中文字符的ASCII值,就可以通过chr()函数组装出中文字符,代码如下
复制代码 代码如下:
$string = "不要迷恋哥";
$length = strlen($string);
var_dump($string);//原始中文
var_dump($length);//长度
$result = array();
for($i=0;$iif(ord($string[$i])>127){
$result[] = ord($string[$i]).' '.ord($string[++$i]);
}
}
var_dump($result);
foreach($result as $v){
$decs = explode(" ",$v);
echo chr($decs[0]).chr($decs[1]);
}

结果如下图
php-chr-dec

如上代码并没有直接输出中文字符,但打印出正常的汉字,其原理是首先获取各个字节的ASCII值,通过chr()函数转化为字节,再把两个字节组合起来就形成了一个完整的中文汉字。

通过对ord()与chr()函数的讨论已经初步了解了中文字符的编码原理,了解GBK编码中一个汉字二个字节,使用ord()与chr()函数实现各字节转换方法,请关注下一期中文字符编码研究系列之中文字符编码转换原理。

参考资料
PHPWind与Discuz截取字符函数substrs与cutstr性能比较

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

See all articles