Skip to content

Instantly share code, notes, and snippets.

@stampycode
Last active April 4, 2017 12:34
Show Gist options
  • Save stampycode/6b16161db66f897766ef858df38e8966 to your computer and use it in GitHub Desktop.
Save stampycode/6b16161db66f897766ef858df38e8966 to your computer and use it in GitHub Desktop.
Render binary data safely in html
<?php
$data = str_split($data, 72);
$color = '#888';
$placeholder = '.';
$repl = function($m) use (&$color, &$placeholder) {
$x = str_repeat($placeholder, strlen($m[0]));
return "<span style=\"background-color:{$color};\">{$x}</span>';
};
foreach($data as &$d) {
$d = str_replace(['<','>'], ['&lt;','&gt;'], $d);
$d = preg_replace_callback('/\x00+/', $repl, $d);
$color = '#f88';
$d = preg_replace_callback('/[\x01-\x0f]+/', $repl, $d);
$color = '#aaf';
$d = preg_replace_callback('/[\x10-\x1f]+/', $repl, $d);
$color = '#fa0';
$d = preg_replace_callback('/[\x7f-\xff]+/', $repl, $d);
$color = '#ccc';
$d = preg_replace_callback('/[^\x20-\x7f]+/', $repl, $d);
}
$data = implode('<br>', $data);
echo $data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment