- Строка в байтовый массив в php
- How to Get the Byte Values of a String in PHP
- How can I get the single bytes from a multibyte PHP string variable in a binary-safe way?
- String to byte array in php
- PHP Read Byte Range from String or File
- String to byte/binary arrays in PHP
- How can I convert array of bytes to a string in PHP?
- array_map()
- foreach()
- pack()
- PHP strlen
- Introduction to the PHP strlen() function
- PHP strlen() function examples
- 1) Simple strlen() function example
- 2) Using the strlen() with a multibyte string
- Summary
- Work Out Size In Bytes Of A PHP String
- Want to know more? Need some help?
- Support Us!
- Comments
- Add new comment
- Related Content
- Generating Histogram Colour Analysis Graphs From Images In PHP
- PHP:CSI — To Switch, Or Not To Switch?
- Drupal 9: Generating Header Images For Pages Of Content Using PHP
- Using PSR-4 With Composer
- Generating A PDF From A Web Page Using PHP And Chrome
- PHP:CSI — Date Is Less Than One Month Ago
Строка в байтовый массив в php
Как я могу получить массив байтов из некоторой строки, которая может содержать числа, буквы и т. Д.? Если вы знакомы с Java, я ищу ту же функциональность метода getBytes ().
Я попробовал такой сниппет:
но безуспешно, поэтому любая помощь будет оценена по достоинству.
PS: Зачем мне это вообще ?? Ну, мне нужно отправить массив байтов через fputs () на сервер, написанный на Java …
@Sparr прав, но я предполагаю, что вы ожидали массив byte[] например byte[] в C #. Это то же самое решение, что и Sparr, но вместо HEX вы ожидали int presentation ( диапазон от 0 до 255 ) каждого char . Вы можете сделать следующее:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog'); var_dump($byte_array); // $byte_array should be int[] which can be converted // to byte[] in C# since values are range of 0 - 255
Используя var_dump вы можете видеть, что элементы являются int ( not string ).
array(44) < [1]=>int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32) [5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107) [10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32) [15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101) [20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101) [25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101) [30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121) [35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119) [40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) >
print_r(unpack("H*","The quick fox jumped over the lazy brown dog")) Array ( [1] => 54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67 )
При необходимости вы можете разделить результат на два столбца с шестнадцатеричным символом.
Вы можете попробовать следующее:
$in_str = 'this is a test'; $hex_ary = array(); foreach (str_split($in_str) as $chr) < $hex_ary[] = sprintf("%02X", ord($chr)); >echo implode(' ',$hex_ary);
В PHP строки – это потоки. Что именно ты пытаешься сделать?
Ps. Зачем мне это вообще ?? Ну, мне нужно отправить через fputs () bytearray на сервер, написанный в java …
fputs принимает строку в качестве аргумента. Скорее всего, вам просто нужно передать свою строку. На стороне Java вещи вы должны декодировать данные в любой кодировке, которую вы используете в php (по умолчанию iso-8859-1).
PHP не имеет явного типа byte , но его string уже является эквивалентом массива байтов Java. Вы можете безопасно писать fputs($connection, «The quick brown fox …») . Единственное, что вы должны знать, это кодирование символов, они должны быть одинаковыми с обеих сторон. Используйте mb_convert_encoding (), когда вы сомневаетесь.
Я нашел несколько функций, определенных в http://tw1.php.net/unpack , очень полезными.
Они могут скрывать строку в байтовый массив и наоборот.
Возьмите byteStr2byteArray () в качестве примера:
$msg = "abcdefghijk"; $byte_array = byteStr2byteArray($msg); for($i=0;$i ?>
How to Get the Byte Values of a String in PHP
How can I get the single bytes from a multibyte PHP string variable in a binary-safe way?
you can get a bytearray by unpacking the utf8_encoded string $a:
$a = utf8_encode('Fön');
$b = unpack('C*', $a);
var_dump($b);
used format C* for «unsigned char»
- String to byte array in php
- http://www.php.net/manual/en/function.unpack.php
- http://www.php.net/manual/en/function.pack.php
String to byte array in php
@Sparr is right, but I guess you expected byte array like byte[] in C#. It’s the same solution as Sparr did but instead of HEX you expected int presentation (range from 0 to 255) of each char . You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump you can see that elements are int (not string ).
array(44) < [1]=>int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) >
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
PHP Read Byte Range from String or File
You should be able to do this with fseek and fread .
$byteOffset = 1024;
$readLength = 256;
$fileHandle = fopen('myfile', 'r');
fseek($fileHandle, $byteOffset);
$bytes = fread($fileHandle, $readLength);
String to byte/binary arrays in PHP
I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:
How can I convert array of bytes to a string in PHP?
If by array of bytes you mean:
$bytes = array(255, 0, 55, 42, 17, );
array_map()
$string = implode(array_map("chr", $bytes));
foreach()
Which is the compact version of:
$string = "";
foreach ($bytes as $chr) $string .= chr($chr);
>
// Might be a bit speedier due to not constructing a temporary array.
pack()
But the most advisable alternative could be to use pack(«C*», [$array. ]) , even though it requires a funky array workaround in PHP to pass the integer list:
$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));
That construct is also more useful if you might need to switch from bytes C* (for ASCII strings) to words S* (for UCS2) or even have a list of 32bit integers L* (e.g. a UCS4 Unicode string).
PHP strlen
Summary: in this tutorial, you’ll learn how to use the PHP strlen() function to get the length of a string.
Introduction to the PHP strlen() function
The strlen() function returns the length of a specified string. Here’s the syntax of the strlen() function:
strlen ( string $string ) : int
Code language: PHP (php)
The strlen() function has one parameter $string , which is the string to measure the length. The strlen() function returns the length of the $string in bytes or zero if the $string is empty.
It’s important to note that the strlen() function returns the number of bytes rather than the number of characters. If each character is 1 byte, the number of bytes is the same as the number of characters.
However, if you deal with the multibyte string, e.g., UTF-8, the number of bytes is higher than the number of characters.
To get the number of characters in a multibyte string, you should use the mb_strlen() function instead:
mb_strlen ( string $string , string|null $encoding = null ) : int
Code language: PHP (php)
The mb_strlen() function has an additional $encoding that specifies the character encoding of the $string .
The mb_strlen() function returns the number of characters in the $string having character $encoding . The mb_strlen() returns one for each multibyte character.
PHP strlen() function examples
Let’s take some examples of using the strlen() function.
1) Simple strlen() function example
The following example uses the strlen() function to return the length of the string PHP:
$str = 'PHP'; echo strlen($str); // 3
Code language: PHP (php)
2) Using the strlen() with a multibyte string
The following multibyte string has five characters. However, its size is 15 bytes.
'こんにちは'
Code language: PHP (php)
By the way, こんにちは is a greeting in Japanese. It means hello in English.
The strlen() function returns 15 bytes for the string ‘こんにちは’ :
$message = 'こんにちは'; echo strlen($message); // 15 bytes
Code language: PHP (php)
But the mb_strlen() function returns five characters for that string:
$message = 'こんにちは'; echo mb_strlen($message); // 5 characters
Code language: PHP (php)
Summary
- 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.
Work Out Size In Bytes Of A PHP String
Note: This post is over two years old and so the information contained here might be out of date. If you do spot something please leave a comment and we will endeavour to correct.
I found this very handy function on the php.net site in the user comments for the strlen() function. It accepts a string in ASCII or UTF-8 format and finds out how long that string is in bytes.
The function works by going through the string and adding how many bytes each character represents. For normal ASCII values this is a single byte so 1 is added to the total. Unicode characters can be up to 6 bytes and so the rest of this function works out how many bytes the character takes up by using AND calculations.
); switch(true)< case(($ord_var_c >= 0x20) && ($ord_var_c ; >; return $d; >
This string is useful if you want to know how large a string is in bytes, but have only a small amount of control over how the string will be presented. For example, if you download a web page and want to know how large it is in bytes you can pass the content of the page into this function.
You might think that the Content-Length header could be used here, but you can’t rely on this header to be returned from every site. Some sites will simply omit the line, whilst others will just put a default amount there.
Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK. Graduating in 2003 from Aberystwyth University with an MSc in Computer Science Phil has previously worked as a database administrator, on an IT help desk, systems trainer, web architect, usability consultant, blogger and SEO specialist. Phil has lots of experience building and maintaining PHP websites as well as working with associated technologies like JavaScript, HTML, CSS, XML, Flex, Apache, MySQL and Linux.
Want to know more? Need some help?
Let us help! Hire us to provide training, advice, troubleshooting and more.
Support Us!
Please support us and allow us to continue writing articles.
Comments
It returned the string lenght not the size in byte.
Submitted by Anonymous on Sat, 04/07/2012 — 22:00
Add new comment
Related Content
Generating Histogram Colour Analysis Graphs From Images In PHP
If you’ve ever looked at the settings in a digital camera, or have experience with image processing programs like GIMP, then you may have seen a colour histogram. This is a simple graph that shows the amount of different shades of colour are present in the image.
PHP:CSI — To Switch, Or Not To Switch?
I was writing unit tests for a API mapping function recently and came across this interesting issue. The code I was writing tests for was in a legacy codebase that I was making changes to, and it made sense to have some unit tests in there before I started work to ensure everything worked before and after.
Drupal 9: Generating Header Images For Pages Of Content Using PHP
Embedding image within pages of content helps both within the design of the page and when shared on social media. If you set up meta tags to point at a particular image then that image will appear when the page is shared on social media. This makes your page stand out more.
Using PSR-4 With Composer
The PHP Standards Recommendations (called PSR) are a set of standards that aim to make certain aspects of working with PHP easier.
Generating A PDF From A Web Page Using PHP And Chrome
Generating a PDF document from a web page through PHP can be problematic. It’s often something that seems quite simple, but actually generating the document can be difficult and time consuming.
PHP:CSI — Date Is Less Than One Month Ago
Working with logic surrounding dates can sometimes be difficult and it’s fairly common to come across really subtle date and time based bugs.
I was recently shown a bug in a PHP application that looks like it should be working at face value, but doesn’t actually produce the correct result.