goocreations
goocreations

Reputation: 3066

PHP - Add null character to string

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?

Upvotes: 4

Views: 16761

Answers (5)

mnrafg
mnrafg

Reputation: 71

Just the following line is enough:

$s = pack('a32', 'hello');

Upvotes: 0

Tim McKinney
Tim McKinney

Reputation: 51

This appears to work:

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

Upvotes: 3

karvin.developer
karvin.developer

Reputation: 556

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

Upvotes: 0

Disfigure
Disfigure

Reputation: 740

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.

Upvotes: 5

t.h3ads
t.h3ads

Reputation: 1878

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

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

Upvotes: 10

Related Questions