Skip to content

Instantly share code, notes, and snippets.

@bgrimes
Created November 12, 2012 21:01
Show Gist options
  • Save bgrimes/4061868 to your computer and use it in GitHub Desktop.
Save bgrimes/4061868 to your computer and use it in GitHub Desktop.
Convert scaled bytes to raw bytes
/**
* Convert string such as '500mb' to bytes. Converts KB, MB, GB, TB, PB) The strings
* are case insensitive (mb=MB=m=M, k=K=kb=KB=Kb=kB)
*
* Usage:
* $bytes = convertToBytes("512kb");
*
* @param string $from
*
* @return bool|integer
*/
public function convertToBytes($from)
{
preg_match('/^(?<from>\d+)(?<scale>[a-zA-Z]+)$/', $from, $matches);
if ( !isset($matches['from']) or !isset($matches['scale']) )
{
return false;
}
$from = $matches['from'];
$scale = $matches['scale'];
// kilobytes
if ( preg_match('/(kb|k)/i', $scale) )
{
return $from*1024;
}
elseif (preg_match('/mb|m/i', $scale) )
{
return $from*pow(1024,2);
}
elseif (preg_match('/gb|g/i', $scale) )
{
return $from*pow(1024,3);
}
elseif (preg_match('/tb|t/i', $scale) )
{
return $from*pow(1024,4);
}
elseif (preg_match('/pb|p/i', $scale) )
{
return $from*pow(1024,5);
}
else
{
return $from;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment