Skip to content

Instantly share code, notes, and snippets.

@Langmans
Created January 29, 2016 08:41
Show Gist options
  • Select an option

  • Save Langmans/4c3a3d27bfd40e159f75 to your computer and use it in GitHub Desktop.

Select an option

Save Langmans/4c3a3d27bfd40e159f75 to your computer and use it in GitHub Desktop.
<?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