What does the b in front of string literals do?
Asked Answered
D

3

28
$binary = b'Binary string';

What consequences does it have to create a string as binary?

I couldn't find any hint about that in the documentation. Just found this little curiosity while looking through the language_scanner.

Deuteranopia answered 20/1, 2011 at 16:3 Comment(4)
This was added in 5.2.1 - What version of PHP are you using?Championship
I'm using PHP 5.3.5. But why is that of importance?Deuteranopia
@RobertPitt: Would it? Wouldn't it at least need to be b . 'String' to be concatenated? Imho it would simple throw Unexpected T_CONSTANT_ENCAPSED_STRING.Deuteranopia
in PHP 5.2 it would just echo Binary String: codepad.org/6XGKX8ES, but it dose throw that syntax error on some versionsPoulterer
B
28

This is a forward compatibility token for the never-to-be-released PHP version 6, which should have had native unicode support.

In PHP6, strings are unicode by default, and functions operate at the unicode character level on them. This "b" means "binary string", that is, a non unicode string, on which functions operate at the byte level.

This has no effect in PHP != 6, where all strings are binary.

Benuecongo answered 20/1, 2011 at 16:12 Comment(3)
Ah, this makes it clear. Interesting that they did this forwards compatibility thing. Are there any other such forwards compat tokens?Deuteranopia
Not that I know of except the related "(binary)" cast token.Benuecongo
So how do I make it go away? Do I need to decode it or something?Gatefold
V
2

Binary casting is available since 5.2.1 but will not take effect until 6.0 when unicode strings also take effect.

Which explains why this does nothing special right now for me on a server using 5.2.6:

<?php
$t = b"hey";
var_dump($t);
//string(3) "hey"

$s = (binary)"hey";
var_dump($s);
//string(3) "hey"
?>
Venery answered 20/1, 2011 at 16:11 Comment(0)
S
0

Convert to string

$binary = preg_replace('/[[:^print:]]/', '', $binary);
Soares answered 27/11, 2019 at 12:1 Comment(1)
Hi, welcome to Stack Overflow. Thanks for taking the time and contributing an answer! Please note, however, that the question was about the 'b' in front of the string and what it means / what's the point of creating a binary string. Your post doesn't actually answer that. If you have general remarks, consider posting them as comments instead of answers once you gained sufficient reputation. Until then, focus on answering the actual questions.Answer

© 2022 - 2024 — McMap. All rights reserved.