Created
November 12, 2012 21:01
-
-
Save bgrimes/4061868 to your computer and use it in GitHub Desktop.
Convert scaled bytes to raw bytes
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
/** | |
* 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