Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 971
lynn Avatar asked Feb 26 '09 17:02

lynn


People also ask

How do you calculate bytes of a string in PHP?

Use the PHP strlen() function to get the number of bytes of a string. Use the PHP mb_strlen() function to get the number of characters in a string with a specific encoding.

How do you get a byte from a string?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

How do you find the value of byte strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java.

Which function returns the number of bytes of a string?

LENB returns the number of bytes used to represent the characters in a text string.


3 Answers

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/>";
}
?>
like image 124
Gautam Avatar answered Oct 05 '22 20:10

Gautam


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!

like image 28
Roman Hocke Avatar answered Oct 05 '22 18:10

Roman Hocke


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

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

Reference

like image 6
Adee Avatar answered Oct 05 '22 18:10

Adee