4

I'm trying to append a number of NULL characters '\0' to a string in PHP.

$s = 'hello';
while(strlen($s) < 32) $s .= '\0';

However, PHP adds 2 characters (\ and 0), instead of escaping the character and adding NULL. Does anyone know to add a NULL character to a string?

goocreations
  • 2,938
  • 8
  • 37
  • 59

5 Answers5

9

I don't know if \0 is correct in your case, but you should use ":

$s = 'hello';
while(strlen($s) < 32) $s .= "\0";
t.h3ads
  • 1,858
  • 9
  • 17
3

Caused by ' you should use ".

Using simple quote PHP doesn't interpret code or special char like (\n\r\0), by using double quote PHP will.

Disfigure
  • 720
  • 6
  • 19
2

This appears to work:

$result = str_pad($str, 32, "\0");
echo strlen($result); // output: 32
0

Try the following code

echo $str="Hello "; echo ' Length : '.strlen($str); while(strlen($str)<32) { $str.=' '; } echo '<br/>'; echo $str; echo ' Length : '.strlen($str);

Hope this will solve your problem

0

Just the following line is enough:

$s = pack('a32', 'hello');
mnrafg
  • 71
  • 1
  • 10