I was looking round the web this afternoon to see if I could find a function to convert from megabytes, kilobytes etc.. to bytes but all I could find were functions to go the other way. So I have written one, and I thought it might help a few people if I shared it on here:
function convert_to_bytes ($string) {
if (preg_match('/([0-9\.]+) ?([a-z]*)/i', $string, $matches)) {
$number = $matches[1];
$suffix = $matches[2];
$suffixes = array(""=> 0, "Bytes"=>0, "KB"=>1, "MB"=>2, "GB"=>3, "TB"=>4, "PB"=>5);
if (isset($suffixes[$suffix])){
$bytes = round($number * pow(1024, $suffixes[$suffix]));
return $bytes;
} else {
return false;
}
} else {
return false;
}
}
// Convert 25.43 MB => 26665288 bytes
echo convert_to_bytes ("25.43 MB");