如何在 PHP 中获取字符串的字节值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/591446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:11:05  来源:igfitidea点击:

How do I get the byte values of a string in PHP?

phpstringasciibytecode

提问by lynn

Say I have a string in php, that prints out to a text file like this:

假设我在 php 中有一个字符串,它会打印到这样的文本文件中:

n?§9q1Fa£

n?§9q1Fa£

How do I get the byte codes of this to my text file rather than the funky ascii characters?

如何将这个字节码而不是时髦的 ascii 字符输入到我的文本文件中?

回答by Gautam

Use the ord function

使用 ord 函数

http://ca.php.net/ord

http://ca.php.net/ord

eg.

例如。

<?php
$var = "n?§9q1Fa£??ó§?_?—Ló]j";

for($i = 0; $i < strlen($var); $i++)
{
   echo ord($var[$i])."<br/>";
}
?>

回答by Roman Hocke

If You wish to get the string as an array of integer codes, there's a nice one-liner:

如果您希望将字符串作为整数代码数组,有一个很好的单行:

unpack('C*', $string)

Beware, the resulting array is indexed from 1, not from 0!

请注意,结果数组的索引是从 1 开始的,而不是从 0 开始!

回答by Adee

If you are talking about the hex value, this should do for you:

如果你在谈论十六进制值,这应该为你做:

$value = unpack('H*', "Stack");
echo $value[1];

Reference

参考

回答by Henrik Paul

Ord()does the trick with an ASCII-charset. If you, however, meddle with multibyte strings (like UTF-8), you're out of luck, and need to hack it yourself.

Ord()用 ASCII 字符集来解决这个问题。但是,如果您使用多字节字符串(如 UTF-8),那您就不走运了,需要自己破解它。