Skip to content

Instantly share code, notes, and snippets.

@lajosbencz
Created September 17, 2015 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lajosbencz/db15c715dd2474e48077 to your computer and use it in GitHub Desktop.
Save lajosbencz/db15c715dd2474e48077 to your computer and use it in GitHub Desktop.
Convert between byte size units
<?php
namespace LajosBencz;
class ConvertByteSize
{
const FORMAT_BYTE_SIZE_PATTERN = '(yotta|zetta|exa|peta|tera|giga|mega|kilo|y|z|e|p|t|g|m|k)\s*(bit|byte|b)?';
public static $formatByteSize_Unit = 'mB';
public static $formatByteSize_Format = '%0.2f %s';
public static function format($value, $unit=null, $format=null) {
if(!$unit) {
$unit = self::$formatByteSize_Unit;
}
if(!$format) {
$format = self::$formatByteSize_Format;
}
static $exponents;
if(!$exponents) {
$exponents = array_flip(['','k','m','g','t','p','e','z','y']);
}
if(preg_match('/'.self::FORMAT_BYTE_SIZE_PATTERN.'/i',$unit,$match)) {
$ru = strtolower($match[1][0]);
$rb = $match[2]?:self::$formatByteSize_Unit[1];
} else {
$ru = self::$formatByteSize_Unit[0];
$rb = self::$formatByteSize_Unit[1];
}
$mru = pow(1024,intval($exponents[$ru]));
$mrb = ($rb == 'b' || $rb == 'bit') ? 8 : 1;
unset($match);
if(preg_match('/([\d\s\.\,]+)\s*(?:'.self::FORMAT_BYTE_SIZE_PATTERN.')?/i',$value,$match)) {
$v = floatval(str_replace([' ',','],['','.'],$match[1]));
$vu = $match[2]?strtolower($match[2][0]):'';
$vb = $match[3]?:'B';
$mvu = pow(1024,intval($exponents[$vu]));
$mvb = ($vb == 'b' || $vb == 'bit') ? 8 : 1;
$v*= $mvu;
$v*= $mvb;
$v/= $mru;
$v*= $mrb;
if(is_callable($format)) {
return call_user_func_array($format,[$v,$unit]);
}
return sprintf($format,$v,$unit);
}
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment