The functions of the PHP package and unpacking, unfortunately, do not provide automatic packaging and unpacking of strings with variables (with zero completion) of the Perl type.
To perform this function, consider moving the unpack function to a helper class as follows:
class Packer { static function unpack($mask, $data, &$pos) { try { $result = array(); $pos = 0; foreach($mask as $field) { $subject = substr($data, $pos); $type = $field[0]; $name = $field[1]; switch($type) { case 'N': case 'n': case 'C': case 'c': $temp = unpack("{$type}temp", $subject); $result[$name] = $temp['temp']; if($type=='N') { $result[$name] = (int)$result[$name]; } $pos += ($type=='N' ? 4 : ($type=='n' ? 2 : 1)); break; case 'a': $nullPos = strpos($subject, "\0") + 1; $temp = unpack("a{$nullPos}temp", $subject); $result[$name] = $temp['temp']; $pos += $nullPos; break; } } return $result; } catch(Exception $e) { $message = $e->getMessage(); throw new Exception("unpack failed with error '{$message}'"); } } }
Please note that this function does not implement all types of unpacking and just serves as an example.
source share