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

情到浓时终转凉″ 提交于 2019-11-26 16:13:46

问题


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

nÖ§9q1Fª£

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


回答1:


Use the ord function

http://ca.php.net/ord

eg.

<?php
$var = "nÖ§9q1Fª£ˆæÓ§Œ_»—Ló]j";

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



回答2:


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!




回答3:


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

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

Reference




回答4:


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.



来源:https://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!