php版本的charCodeAt()函数

作者:matrix 被围观: 7,320 次 发布时间:2014-03-29 分类:兼容并蓄 零零星星 | 17 条评论 »

这是一个创建于 3675 天前的主题,其中的信息可能已经有所发展或是发生改变。

charCodeAt()函数方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。
JavaScript里经常看到charCodeAt函数但有些时候需要转换为php,这下就哦豁了。php里没有这玩意~ 自己写又搞不来。

还好,网上有一大把的代码:


function get_bianma($str)//等同于js的charCodeAt() { $result = array(); for($i = 0, $l = mb_strlen($str, 'utf-8');$i < $l;++$i) { $result[] = uniord(mb_substr($str, $i, 1, 'utf-8')); } return join(",", $result); } function uniord($str, $from_encoding = false) { $from_encoding = $from_encoding ? $from_encoding : 'UTF-8'; if (strlen($str) == 1) return ord($str); $str = mb_convert_encoding($str, 'UCS-4BE', $from_encoding); $tmp = unpack('N', $str); return $tmp[1]; }

说明:

get_bianma(substr($f, $e, 1))等同于js代码$f.charCodeAt($e)

表示获取$f中的第$e个位置的字符的 Unicode 编码

其他文章:
本文固定链接:https://www.hhtjim.com/the-php-version-of-the-charcodeat-function.html
matrix
本文章由 matrix 于2014年03月29日发布在兼容并蓄, 零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:php版本的charCodeAt()函数-HHTjim'S 部落格
关键字:, ,

有17 条评论 »

  1. 米兔 米兔 2022-10-15 10:00:32 +0800#7

    大佬,我前端是gbk用charCodeAt(a).toString(16)转为十六进制,然后用你的代码反转不出来原来的中文,这是咋回事。

    • matrix matrix Moderator 2022-10-15 12:05:57 +0800

      文章里面的函数是编码的。解码可以用mb_chr处理

      mb_chr(21834,'UTF-8');
      
      • test test 2022-10-15 18:18:20 +0800

        mb_chr还是解不了,出来是的空白。
        exit(mb_chr(6211, 'gbk')); //6211是前端gbk编码的【我】字,js charCodeAt(a).toString(16)

        • matrix matrix Moderator 2022-10-15 18:44:01 +0800

          不清楚前端gbk编码的
          ```php
          var_dump( mb_chr(hexdec(6211) , 'utf-8') );// string(3) "我"
          ````
          这是想要的结果?

          • test test 2022-10-15 19:00:56 +0800

            对,是这样,原来要把16进制转成10进制才行的吗

            • matrix matrix Moderator 2022-10-15 19:08:06 +0800

              系统默认读取10进制数字,除非你显示申明

              var_dump( mb_chr(0x6211, 'utf-8') );
              

              0x6211 就表示你输入的是16进制数

              • test test 2022-10-15 19:36:52 +0800

                ok,明白了,感谢。 😀

      • test test 2022-10-15 18:30:42 +0800

        难道前端charCodeAt(a).toString(16);编码,只有在前端才能解码,后端PHP解不了前端的么??纳闷。

  2. 谷歌优化 谷歌优化 2022-10-10 9:43:12 +0800#6

    背景主题很可爱啊

  3. 未知路 未知路 2014-4-13 21:01:32 +0800#5

    正在学PHP。博主有什么好的教程可以推荐的吗?

    • Matrix Matrix Moderator 2014-4-14 13:02:26 +0800

      这个教程不错 http://pan.baidu.com/s/1dDtcwnv

      不过我还没看

  4. 厦门品讯 厦门品讯 2014-4-9 10:20:52 +0800#4

    不错哦 顶一个

  5. 快乐淘 快乐淘 2014-4-7 15:47:59 +0800#3

    😡 对代码什么的最无力了,脑洞太大,看不懂。。。。

    • Matrix Matrix Moderator 2014-4-7 19:00:47 +0800

      先了解点基本语法 后面就慢慢懂了

  6. mooc mooc 2014-3-30 10:18:43 +0800#2

    😯

  7. 逗妇乳 逗妇乳 2014-3-29 22:37:03 +0800#1

    最近在研究网络小说 😛

    • Matrix Matrix Moderator 2014-3-29 23:10:35 +0800

      应该很来钱吧 😀

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!