search
HomeBackend DevelopmentPHP Tutorialphp的ord函数??解决中文字符截断问题

函数是这样定义的:

int ord ( string$string)

返回字符串 string 第一个字符的 ASCII 码值。

该函数是chr()的互补函数。

试一下:

echo ord('我');
这里只能返回230, 我是以u8保存的文件并输出的, 它得到的只有230, 而230转换成hex是e6,实际上utf-8中我的编码是e68891, 它只拿到了第一个字节
echo chr(0xe6).chr(0x88).chr(0x91);

这个例子可以在utf-8的情况下输出”我“这个汉字

如果大家想了解字符编码的问题可以点这里字符编码

如果大家想查看一个汉字的gbk,utf-8,unicode各种编码方式推荐大家用Notepad++下的HEX-editor点击这里下载:

http://pan.baidu.com/s/1hquyJwo

长这样子


提高逼格:

身为一个程序猿,除了是苦逼的代名词外,还是神秘的象征,偶尔装XX还是不错的。既然说到编码,

那我们就说说属于你的字吧,在utf-8编码的世界里,可不是每个人都能找到属于自己的那款哦,

‘我’的编码是三字节,分别为e6、88、91,如果把你的生日放进去能编出啥字呢,想想是不是还有点小激动,

例如你是1988-9-4出生,那对应的属于自己的三字节为e9、88、94,anyway这个方法你也可以自己点,

爆个料,按照此方法,我的字是‘釉’,好字啊,you you 切克闹。

按照此法为啥不是每个人都有呢,那自己读下utf-8的二进制存储规则就知道了,

哈哈,还是点这里字符编码

扯了一堆没用的,其实就是希望大家发现编码的乐趣


自己动手:

很久以前是没有mb_substr函数的,因此带汉字的字符串截断操作处理起来很麻烦,不过现在可以直接用它。

既然我们对字符编码和ord函数有了很好的了解,自己就写个针对utf-8编码的字符串截断的函数吧。

代码很戳,有待优化,但理解起来简单,贴过去可以运行,基本场景也考虑到了,还算欣慰;

<?php $a = "jf我们de没";    /**     * @brief     *     * @param $str 待截取的字符串    * @param $start 字符串开始位置     * @param $num  截取到多长的字符串     *     * @return     */    function utf8_substr($str, $start, $num){        $res = '';      //存储截取到的字符串        $cnt = 0;       //计数器,用来判断字符串是否走到$start位置        $t = 0;         //计数器,用来判断字符串已经截取了$num的数量        for($i = 0; $i < strlen($str); $i++){            if(ord($str[$i]) > 127){    //非ascii码时                if($cnt >= $start){     //如果计数器走到了$start的位置                    $res .=$str[$i].$str[++$i].$str[++$i]; //utf-8是三字节编码,$i指针连走三下,把字符存起来                    $t ++;              //计数器++,表示我存了几个字符串了到$num的数量就退出了                }else{                      $i++;               //如果没走到$start的位置,那就只走$i指针,字符不用处理                    $i++;                   }                       $cnt ++;            }else{                  if($cnt >= $start){     //acsii码正常处理就好                    $res .=$str[$i];                    $t++;                   }                       $cnt ++;                                    }                   if($num == $t) break;       //ok,我要截取的数量已经够了,我不贪婪,我退出了        }               return $res;    }    var_dump(utf8_substr($a, 3, 10));   //结果应该是你想要的?>




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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

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-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

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' =>

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.

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

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)