简体   繁体   中英

Can't concatenate x codes (\x) - PHP

I'm looking to use unpack().

This works:

$srbytes = "\x80\x3e\x00\x00";

$array1 = unpack("v",$srbytes); 

This does not:

$num1 = "80"

$srbytes = "\x".$num1."\x3e\x00\x00";

$array1 = unpack("v",$srbytes);

or

$srbytes = "\x"."80\x3e\x00\x00"; 
$array1 = unpack("v",$srbytes);

Printing this with echo shows ASCII chars with the first full string but, the concatenated ones shows text until it passes where it was concatenated.

Comparing a full string against a concatenated ones shows false, even though they should be the same?

what is actually happening when I'm trying to concatenate

The character expansion won't work, because at the point that you do "\\x" . "80" "\\x" . "80" PHP already has two string literals . It can't be expected to figure that meant anything else but this.

Instead of trying to concatenate a hexadecimal value for expansion, just concatenate the actual character, by converting the hexadecimal value to a base10 integer, and passing it to chr() , which converts it to an actual byte.

$str = "";
$num1 = "80";
$str .= chr(base_convert($num1, 16, 10));
var_dump($str);

Gives you

string(1) "�"

When you actually look at the value of $srbytes in your example where you define it as a string literal "\\x80\\x3e\\x00\\x00" , what you get is var_dump("\\x80\\x3e\\x00\\x00") giving you string(4) " >" , because PHP double quoted strings offer additional character expansion such as expanding on escaped hexadecimal values into bytes. However, var_dump("\\x"."80\\x3e\\x00\\x00") just gives you string(7) "\\x80>" , which is because the value "\\x" by itself is just a literal "\\x" as a string. So they aren't the same values, no.

If you want the 'literal' string use single quotes. Your issue is with escaped character sequences inside double quotes being evaluated. Example:

$srbytes = '\x'.'80\x3e\x00\x00'; 
echo $srbytes;
// \x80\x3e\x00\x00
var_dump($srbytes);
// string(16) "\x80\x3e\x00\x00" 

$srbytes = "\x"."80\x3e\x00\x00"; 
echo $srbytes;
// \x80>
var_dump($srbytes);
//string(7) "\x80>"

http://php.net/manual/en/language.types.string.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM