search
HomeBackend DevelopmentPHP TutorialPHP函数篇之掌握ord()与chr()函数应用_PHP

中文字符编码研究系列第三期,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
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 Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.