Last active
January 4, 2023 16:27
-
-
Save inxilpro/a5d68f37b3b68bce55409be19e72f57f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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