Skip to content

Instantly share code, notes, and snippets.

@inxilpro
Last active January 4, 2023 16:27
Show Gist options
  • Select an option

  • Save inxilpro/a5d68f37b3b68bce55409be19e72f57f to your computer and use it in GitHub Desktop.

Select an option

Save inxilpro/a5d68f37b3b68bce55409be19e72f57f to your computer and use it in GitHub Desktop.
<?php
$value = '4 mb';
$units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$aliases = ['k' => 1, 'kiB' => 1, 'm' => 2, 'MiB' => 2, 'g' => 3, 'GiB' => 3, 't' => 4, 'TiB' => 4, 'PiB' => 5, 'EiB' => 6, 'ZiB' => 7, 'YiB' => 8];
preg_match('/([0-9,.]+)\s*([a-z]+)/i', $value, $matches);
[$_, $size, $unit] = $matches;
$size = (float) str_replace(',', '', $size);
$lookup = collect($units)
->combine(array_keys($units))
->union($aliases);
$exponent = $lookup->first(fn($exponent, $key) => 0 === strcasecmp($key, $unit));
$multiplier = 1000 ** $exponent;
$bytes = $size * $multiplier;
$unit = $units[$exponent];
dump("'{$value}' was normalized to '{$size}{$unit}' and converted to '{$bytes} bytes'");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment