nus nus - 1 year ago 82
PHP Question

PHP - How do I generate strings with control characters or binary data?

For testing purposes I need strings such as:


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.

Answer Source

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)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download