2

For testing purposes I need strings such as:

"test\x00string"

I would like to loop over the control characters (00-1F) and generate the strings automatically so I don't have to clutter my code with 31 lines like this but don't know how to realize that in php.

Also for testing malformed utf I might want to insert other byte sequences into strings.

4
  • Have you tried chr()? php.net/manual/en/function.chr.php Commented May 17, 2012 at 19:20
  • @Jack I tried searching for "php generate strings with control characters" and stuff like that. Commented May 17, 2012 at 19:57
  • @Jack I also look at the php documentation for strings Commented May 17, 2012 at 20:00
  • @JackManey I also tried searching SO because I thought someon must have asked this, and otherwise I will, since it is the kind of question you can search for hours on it, but someone can probably answer it in 2 seconds. That's worth taxing someone no? Commented May 17, 2012 at 20:07

2 Answers 2

4

For certain characters there are predefined escape sequences, which can be used in double quotes:

$nullByte = "\0";

However, if you're gonna loop, your best bet would be chr():

$string = '';

foreach (range( 0x00, 0x1F ) as $i)
{
    $string .= chr($i);
}

And as a one-liner:

$string = implode('', array_map('chr', range(0x00, 0x1F)));
Sign up to request clarification or add additional context in comments.

1 Comment

The link to escape sequences it incorrect, as php.net/manual/en/regexp.reference.escape.php is specifically for regex, not for general strings. I'm editing this answer to correct it.
1
$nullByte = chr(0);

You can just concatenate bytes to make a multibyte string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.