<?php
function lzw_compress($string) {
// compression
$dictionary = array_flip(range("\0", "\xFF"));
$word = "";
$codes = array();
for ($i=0; $i <= strlen($string); $i++) {
$x = substr($string, $i, 1);
if (strlen($x) && isset($dictionary[$word . $x])) {
$word .= $x;
} elseif ($i) {
$codes[] = $dictionary[$word];
$dictionary[$word . $x] = count($dictionary);
$word = $x;
}
}
// convert codes to binary string
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$return = "";
$rest = 0;
$rest_length = 0;
foreach ($codes as $code) {
$rest = ($rest << $bits) + $code;
$rest_length += $bits;
$dictionary_count++;
if ($dictionary_count >> $bits) {
$bits++;
}
while ($rest_length > 7) {
$rest_length -= 8;
$return .= chr($rest >> $rest_length);
$rest &= (1 << $rest_length) - 1;
}
}
return $return . ($rest_length ? chr($rest << (8 - $rest_length)) : "");
}
/** LZW decompression
* @param string compressed binary data
* @return string original data
*/
function lzw_decompress($binary) {
$dictionary_count = 256;
$bits = 8;
$codes = array();
$rest = 0;
$rest_length = 0;
mb_internal_encoding("UTF-8");
for ($i = 0; $i < mb_strlen($binary); $i++ ) {$codes[] = mb_ord(mb_substr($binary, $i, 1)); }
// decompression
$dictionary = range("\0", "\xFF");
$return = "";
foreach ($codes as $i => $code) {
$element = $dictionary[$code];
if (!isset($element)) $element = $word . $word[0];
$return .= $element;
if ($i) $dictionary[] = $word . $element[0];
$word = $element;
}
return $return;
}
function mb_ord($string) {
if (extension_loaded('mbstring') === true) {
mb_language('Neutral');
mb_internal_encoding('UTF-8');
mb_detect_order(array('UTF-8', 'ISO-8859-15', 'ISO-8859-1', 'ASCII'));
$result = unpack('N', mb_convert_encoding($string, 'UCS-4BE', 'UTF-8'));
if (is_array($result) === true) return $result[1];
}
return ord($string);
}
echo lzw_compress('');
- Output for 8.1.19 - 8.1.30, 8.2.6 - 8.2.24, 8.3.0 - 8.3.12
- Fatal error: Cannot redeclare mb_ord() in /in/cfa0n on line 75
Process exited with code 255. - Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.18, 8.2.0 - 8.2.5
- Fatal error: Cannot redeclare mb_ord() in /in/cfa0n on line 67
Process exited with code 255. - Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33
- Fatal error: Cannot redeclare mb_ord() in /in/cfa0n on line 76
Process exited with code 255. - Output for 4.3.2 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33
- Output for 4.3.0 - 4.3.1
Process exited with code 137.
preferences:
82.98 ms | 409 KiB | 5 Q