Here is another way to get the result in bytes using PHP8
<?php
/**
* @param string $size
* @return int
* @author DevsrealmGuy
*/
public function getBytes(string $size): int
{
$size = trim($size);
#
# Separate the value from the metric(i.e MB, GB, KB)
#
preg_match('/([0-9]+)[\s]*([a-zA-Z]+)/', $size, $matches);
$value = (isset($matches[1])) ? $matches[1] : 0;
$metric = (isset($matches[2])) ? strtolower($matches[2]) : 'b';
#
# Result of $value multiplied by the matched case
# Note: (1024 ** 2) is same as (1024 * 1024) or pow(1024, 2)
#
$value *= match ($metric) {
'k', 'kb' => 1024,
'm', 'mb' => (1024 ** 2),
'g', 'gb' => (1024 ** 3),
't', 'tb' => (1024 ** 4),
default => 0
};
return (int)$value;
}
#
# TEST: This default to 0 if it doesn't conform with the match standard
#
echo getBytes('2GB') . "</br>";
# OUTPUT: 2147483648
echo getBytes('4tb') . "</br>";
# OUTPUT: 4398046511104
echo getBytes('5345etrgrfd') . "</br>";
# OUTPUT: 0
echo getBytes('357568336586') . "</br>";
# OUTPUT: 0
?>