Created
January 29, 2016 08:41
-
-
Save Langmans/4c3a3d27bfd40e159f75 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 | |
| // https://en.wikipedia.org/wiki/Binary_prefix | |
| function binairy_prefix_to_number($string, $mult = null, $exceptions = true) | |
| { | |
| if (is_numeric($string)) { | |
| return $string; | |
| } | |
| $units = array('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y'); | |
| $pattern = sprintf('@^(?<size>\d+([\.,]\d{1,2})?)(?<unit>[%s]?)(?<binary>i?)b?$@i', implode('', $units)); | |
| preg_match($pattern, $string, $matches); | |
| if (!$matches) { | |
| if ($exceptions) { | |
| throw new \InvalidArgumentException( | |
| sprintf('Pattern %s does not match %s', | |
| var_export($pattern, true), | |
| var_export($string, true))); | |
| } | |
| return $string; | |
| } | |
| $matches += array( | |
| 'size' => 0, | |
| 'unit' => '', | |
| 'binary' => '', | |
| ); | |
| $matches['unit'] = str_replace(',', '.', $matches['unit']); | |
| if (!$mult) { | |
| $mult = $matches['binary'] ? 1024 : 1000; | |
| } | |
| return ceil($matches['size'] * pow($mult, array_search($matches['unit'], $units))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment