Created
September 17, 2015 21:57
-
-
Save lajosbencz/db15c715dd2474e48077 to your computer and use it in GitHub Desktop.
Convert between byte size units
This file contains 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 | |
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