php ord函数,PHP之string之ord()函数使用

ord

(PHP 4, PHP 5, PHP 7)

ord — Return ASCII value of character

ord — 返回字符的 ASCII 码值

Description

int ord ( string $string )

//Returns the ASCII value of the first character of string.

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

//This function complements chr().

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

Parameters

string

A character.

一个字符。

Return Values

Returns the ASCII value as an integer.

返回整型的 ASCII 码值。

Examples

/**

* Created by PhpStorm.

* User: zhangrongxiang

* Date: 2018/2/18

* Time: 下午9:43

*/

$str = 'abcdef';

for ( $i = 0; $i < strlen( $str ); $i ++ ) {

echo $str[ $i ] . ' : ' . ord( $str{$i} ) . PHP_EOL;

}

/*

* a : 97

* b : 98

* c : 99

* d : 100

* e : 101

* f : 102

*/

echo ord( 'a' ) . PHP_EOL;//97

echo ord( 'b' ) . PHP_EOL;//98

function ordutf8( $string, &$offset ) {

$code = ord( substr( $string, $offset, 1 ) );

$bytesnumber = 0;

if ( $code >= 128 ) { //otherwise 0xxxxxxx

if ( $code < 224 ) {

$bytesnumber = 2;

} //110xxxxx

else if ( $code < 240 ) {

$bytesnumber = 3;

} //1110xxxx

else if ( $code < 248 ) {

$bytesnumber = 4;

} //11110xxx

$codetemp = $code - 192 - ( $bytesnumber > 2 ? 32 : 0 ) - ( $bytesnumber > 3 ? 16 : 0 );

for ( $i = 2; $i <= $bytesnumber; $i ++ ) {

$offset ++;

$code2 = ord( substr( $string, $offset, 1 ) ) - 128; //10xxxxxx

$codetemp = $codetemp * 64 + $code2;

}

$code = $codetemp;

}

$offset += 1;

if ( $offset >= strlen( $string ) ) {

$offset = - 1;

}

return $code;

}

$text = "中国?";

$offset = 0;

while ( $offset >= 0 ) {

//0: 20013

//3: 22269

//6: 128516

echo $offset . ": " . ordutf8( $text, $offset ) . PHP_EOL;

}

function uniord( $u ) {

$k = mb_convert_encoding( $u, 'UCS-2LE', 'UTF-8' );

$k1 = ord( substr( $k, 0, 1 ) );

$k2 = ord( substr( $k, 1, 1 ) );

return $k2 * 256 + $k1;

}

echo uniord( "中" ) . PHP_EOL;//20013

echo uniord( "国" ) . PHP_EOL;//22269

//error

echo uniord( '?' ) . PHP_EOL;//63

See

All rights reserved

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值